In this blog post, we will learn how to iterate over a dictionary in C#.
We will use a few different ways to iterate over the dictionary.
Let's first create a dictionary and then try to iterate over the dictionary to use it's keys and values.
Iterate Over Dictionary Using Foreach Loop In C#
Let's create a dictionary of country names with key value pairs.
Dictionary
Now, we will iterate through this dictionary using a foreach loop and we will access it's key and value pair.
Dictionary
Result:
Country Code: USA, Country Name: United States Of America Country Code: IND, Country Name: India Country Code: NZ, Country Name: New Zealand Country Code: AUS, Country Name: Australia Country Code: BR, Country Name: Brazil
As we can see from above example, we have iterated over a dictionary in C# using the foreach loop.
Using the foreach loop, we use the KeyValuePair to get the key and the value for the element.
Iterate Over Dictionary Using For Loop In C#
Using the same example as above, we will use the for loop to iterate the dictionary and the use the ElementAt method to get the key and value for the element.
Dictionary
Result:
Country Code: USA, Country Name: United States Of America Country Code: IND, Country Name: India Country Code: NZ, Country Name: New Zealand Country Code: AUS, Country Name: Australia Country Code: BR, Country Name: Brazil