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.
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
.
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);}}}
Let's now look at the explanation of the above coding example:
Line 6: We declare a new variable named MyDict
and initialize it with a new instance of the Dictionary<string, string>
class. This dictionary stores key-value pairs where both the keys and values are of type string
.
Lines 7–9: We add a new key-value pair to the MyDict
dictionary. In this example, key1
, key2
, and key3
are the keys of the MyDict
dictionary and value1
, value2
, and value3
are the corresponding values to these keys, respectively.
Line 11: We write a foreach
loop that iterates over each key-value pair in the MyDict
dictionary. During each iteration, the current key-value pair is stored in the pair
variable, which is of type KeyValuePair<string, string>
.
Line 12: This line outputs the current key-value pair. It uses the Console.WriteLine
method to format the output. The placeholders {0}
and {1}
are replaced with the values of the pair.Key
and pair.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