Mid Collections

How do you iterate over a Dictionary<TKey, TValue>?

Use a foreach loop with KeyValuePair<TKey, TValue>:

foreach (KeyValuePair<string, int> pair in dictionary)

Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");

Or use deconstruction (C# 7+):

foreach (var (key, value) in dictionary)

Console.WriteLine($"{key} = {value}");

Follow:

More from C# Programming Tutorial

All questions for this course