C# How To Loop Through a Dictionary
Loop Through a Dictionary
Use a foreach loop to go through all the key/value pairs of a Dictionary:
Example
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Liam", 32);
ages.Add("Jenny", 28);
ages.Add("Angie", 45);
foreach (KeyValuePair<string, int> person in ages)
{
Console.WriteLine(person.Key + " is " + person.Value + " years old");
}
If you only need the keys, loop through the Keys property:
Example
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Liam", 32);
ages.Add("Jenny", 28);
ages.Add("Angie", 45);
foreach (string name in ages.Keys)
{
Console.WriteLine(name);
}
Explanation:
Each item in a dictionary is a KeyValuePair. person.Key is the key (the name), and person.Value is the value (the age).
Use the Values property in the same way to loop through only the values.