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:
  1. Dictionary myDict = new Dictionary()
  2. {
  3. {"apple", 1},
  4. {"banana", 2},
  5. {"cherry", 3}
  6. };
  7. foreach (KeyValuePair kvp in myDict)
  8. {
  9. Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
  10. }
Output:
  1. Key = apple, Value = 1
  2. Key = banana, Value = 2
  3. Key = cherry, Value = 3
Using a 'for' loop:
  1. Dictionary myDict = new Dictionary()
  2. {
  3. {"apple", 1},
  4. {"banana", 2},
  5. {"cherry", 3}
  6. };
  7. for (int i = 0; i < myDict.Count; i++)
  8. {
  9. Console.WriteLine("Key = {0}, Value = {1}", myDict.ElementAt(i).Key, myDict.ElementAt(i).Value);
  10. }
Output:
  1. Key = apple, Value = 1
  2. Key = banana, Value = 2
  3. 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