I want to convert a code from JavaScript to C#. in javascript we can use an object easily as follows, this function returns the indices of the elements that their addition is equal to the target
const nums = [1, 5, 6, 7, 10]; const target = 12; var twoSum = function(nums, target) { let obj = {}; for (i=0;i<nums.length;i++){ let found = target-nums[i]; if(obj[found] != null){ return [obj[found], i] }else{ obj[nums[i]] = i; } } }
the return of the function will be [1,3] which is an array of the indices of 5,7 (as 5+7 = 12)
So what is a similar way to accomplish this solution in c#? Is this applicable by using Objects in C#? or even Arrays/Lists/Dictionaries? What is the best way?
Thanks
Advertisement
Answer
You can do that in JavaScript because arrays are secretly objects here.
In C# it will be a little more complicated because you can’t enlarge arrays like that.
You can use List
, but you will have to increase the length and insert null
s in between.
I suggest using a dictionary because it’s similar to JavaScript’s object.
var nums = new Dictionary<int, int>() { { 0, 1 }, { 1, 5 }, { 2, 6 }, { 3, 7 }, { 4, 10 } }
Then you can iterate like that:
foreach(KeyValuePair<int, int> entry in nums) { // do something with entry.Value or entry.Key }