Start learning free

LESSON 225 OF 674 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Looping Over a Dictionary in C#

Lesson

TL ; DR:

A foreach loop over a Dictionary visits every entry. Each entry has a Key and a Value.


Dictionary<string, int> stock = new Dictionary<string, int>();
stock["apples"] = 5;
stock["pears"] = 2;

foreach (var pair in stock) {
    Console.WriteLine(pair.Key + " " + pair.Value);
}

// apples 5
// pears 2   (no order is promised)


Full lesson:

A loop can visit every entry of a dictionary, one at a time. The loop body runs once per key.

Each entry is a KeyValuePair<string, int>. var lets C# work out that type for you.

Loop over stock.Keys to get only the keys. You can still read each value with its key.

foreach (string fruit in stock.Keys) {
    Console.WriteLine(fruit + " " + stock[fruit]);
}

The order: a Dictionary doesn't promise any order. Don't count on the order you added the keys in. A total or a count comes out the same in any order. Those are safe answers.

Watch out: don't add keys inside the loop. C# stops with an InvalidOperationException.


Your task

A game keeps each player's points in scores. The variables total and count start at 0.

Loop over scores. Add each entry's Value to total. Count the players with 10 points or more in count.

The code at the bottom prints both.

Expected output:

43
2
STEP 1 OF 3
    Ctrl + Enter to check