C# vs. Javascript Foreach

     This article is about a certain style of writing in Javascript that I like use when iterating through an array combined with a foreach which looks something like the following...
var someArray = ["1", "2", "3"];
$.foreach(someArray, function(key, value){
         console.log(key + " , " + value);
});
     Ultimately when I tried to take this same concept over to C# the style did not convert over in the exact same way. I found that the temp variable being used to iterate with did not have any values that tracked where it was in place of the iteration. I found myself asking a similar question in how do you get the index of the current iteration of a foreach loop? To see what I tried you can look at another person's problem where I had attempted in the same manner. Attempting to use the "current" value in the GetEnumerator() sadly does not work.

Solution
     To summarize the answer for this problem the "foreach" uses the Ienumerable  interface to iterate over an object and simply does not have a property to keep track of its place at runtime. I could create something customized to work with all my "foreach" calls, but I just went with a simple approach to make it easier to go back and understand. Nice knowledge under your my belt that "foreach" uses IEnumerable!
int key = 0;
var someArray = ["1", "2", "3"];
foreach(var value in someArray)
{
    print.ln(key +" , " + value);
    key++;
}
Resources
JavaScript Array Object
Arrays Tutorial (C#)
.each() | jQuery API Documentation

Comments

Popular posts from this blog

Nginx Best Practices Extended

Installing Windows on Acer chromebook 15 cb3-532

Entity Framework: ToListAynsc & WhereAsync