How to iterate over a dictionary in C#
A dictionary is a type of collection in C# that stores elements as key/value pairs. It does not maintain a specific order for its elements.
Syntax
Here is the syntax on how to define a dictionary in C#:
Dictionary<int, string> MyDict = new Dictionary<int, string>();
In the above example, the MyDict dictionary holds key-value pairs where the keys are of type int and the values are of type string.
Example
Let's now learn about how we can iterate over a dictionary in C# using the coding example below:
using System;using System.Collections.Generic;class MainClass {public static void Main (string[] args) {Dictionary<string, string> MyDict = new Dictionary<string, string>();MyDict.Add("key1", "value1");MyDict.Add("key2", "value2");MyDict.Add("key3", "value3");foreach (KeyValuePair<string, string> pair in MyDict) {Console.WriteLine("{0} = {1}", pair.Key, pair.Value);}}}
Explanation
Let's now look at the explanation of the above coding example:
Line 6: We declare a new variable named
MyDictand initialize it with a new instance of theDictionary<string, string>class. This dictionary stores key-value pairs where both the keys and values are of typestring.Lines 7–9: We add a new key-value pair to the
MyDictdictionary. In this example,key1,key2, andkey3are the keys of theMyDictdictionary andvalue1,value2, andvalue3are the corresponding values to these keys, respectively.Line 11: We write a
foreachloop that iterates over each key-value pair in theMyDictdictionary. During each iteration, the current key-value pair is stored in thepairvariable, which is of typeKeyValuePair<string, string>.Line 12: This line outputs the current key-value pair. It uses the
Console.WriteLinemethod to format the output. The placeholders{0}and{1}are replaced with the values of thepair.Keyandpair.Value, respectively. As a result, each key-value pair in the dictionary will be printed.
Here is the output of the above coding example:
key1 = value1key2 = value2key3 = value3
Free Resources