Thursday, April 20, 2023

How to iterate over a dictionary in C# ?

In C#, you can iterate over a dictionary using a 'foreach' loop or a 'for' loop. Here are examples of both approaches:

Using a 'foreach' loop:
Dictionary myDict = new Dictionary()
{
    {"apple", 1},
    {"banana", 2},
    {"cherry", 3}
};

foreach (KeyValuePair kvp in myDict)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Output:
Key = apple, Value = 1
Key = banana, Value = 2
Key = cherry, Value = 3
Using a 'for' loop:
Dictionary myDict = new Dictionary()
{
    {"apple", 1},
    {"banana", 2},
    {"cherry", 3}
};

for (int i = 0; i < myDict.Count; i++)
{
    Console.WriteLine("Key = {0}, Value = {1}", myDict.ElementAt(i).Key, myDict.ElementAt(i).Value);
}
Output:
Key = apple, Value = 1
Key = banana, Value = 2
Key = cherry, Value = 3
Note that when using a 'foreach' loop, the loop variable 'kvp' is of type 'KeyValuePair', where 'TKey' and 'TValue' are the types of the dictionary's keys and values, respectively. When using a 'for' loop, you can access the dictionary's elements using the 'ElementAt' method, which returns an element at a specified index.

No comments:

Post a Comment