C# Dictionary Foreach - Iterate Over Dictionary C#

Sameer Saini April 05, 2022
C# Dictionary Foreach - Iterate Over Dictionary C#

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 countries = new Dictionary { { "USA", "United States Of America" }, { "IND", "India" }, { "NZ", "New Zealand" }, { "AUS", "Australia" }, { "BR", "Brazil" } };

Now, we will iterate through this dictionary using a foreach loop and we will access it's key and value pair.

Dictionary countries = new Dictionary { { "USA", "United States Of America" }, { "IND", "India" }, { "NZ", "New Zealand" }, { "AUS", "Australia" }, { "BR", "Brazil" } }; foreach (var country in countries) { Console.WriteLine($"Country Code: {country.Key}, Country Name: {country.Value}"); }

 

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 countries = new Dictionary { { "USA", "United States Of America" }, { "IND", "India" }, { "NZ", "New Zealand" }, { "AUS", "Australia" }, { "BR", "Brazil" } }; for (int i = 0; i < countries.Count; i++) { Console.WriteLine($"Country Code: {countries.ElementAt(i).Key}, Country Name: {countries.ElementAt(i).Value}"); }

 

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