loop over a dictionary in csharp

In C#, you can iterate over a dictionary using either a foreach loop or a for loop. Here's an example of how to use a foreach loop:

main.cs
Dictionary<string, int> myDict = new Dictionary<string, int>
{
    { "apple", 1 },
    { "banana", 2 },
    { "orange", 3 }
};

foreach (KeyValuePair<string, int> kvp in myDict)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
251 chars
12 lines

Output:

main.cs
Key = apple, Value = 1
Key = banana, Value = 2
Key = orange, Value = 3
71 chars
4 lines

Alternatively, you can use a for loop to iterate over the dictionary's Keys or Values:

main.cs
for (int i = 0; i < myDict.Count; i++)
{
    Console.WriteLine("Key = {0}, Value = {1}", myDict.Keys.ElementAt(i), myDict.Values.ElementAt(i));
}
146 chars
5 lines

Output:

main.cs
Key = apple, Value = 1
Key = banana, Value = 2
Key = orange, Value = 3
71 chars
4 lines

gistlibby LogSnag