Loop through System.Collections.Generic.Dictionary via for statement

c#, generics, loops

Solution

Not in a reasonable way, no. You could use the Linq extension `ElementAt`:

for (int i = 0; i < dictionary.Keys.Count; i++)
{
    Console.WriteLine(dictionary.ElementAt(i).Value);                
}

...but I really don't see the point. Just use the regular `foreach` approach. If you for some reason need to keep track of an index while iterating, you can do that "on the side":

int index = 0;
foreach (var item in dictionary)
{
    Console.WriteLine(string.Format("[{0}] - {1}", index, item.Value));

    // increment the index
    index++;
}

Problem

I have a quick question. Is there way to easy loop through `System.Collections.Generic.Dictionary` via `for` statement in C#? Thanks in advance.

Original source