c# · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Count with a dictionary, then visit every pair.
A counts how often each thing turns up. Go through the items one by one. If the dictionary already has the item as a key, add one to its value with ++. If not, start it at 1.
foreach (var pair in tally) visits every pair in turn. Each pair is a with two parts: pair.Key and pair.Value.
A plain Dictionary makes no promise about order, so its pairs might come out any way round. A works the same but keeps its keys sorted, so a loop visits them from A to Z.
using System;
using System.Collections.Generic;
string[] votes = { "pizza", "tacos", "pizza", "sushi", "pizza" };
var tally = new SortedDictionary<string, int>();
foreach (string vote in votes)
{
if (tally.ContainsKey(vote))
{
tally[vote]++;
}
else
{
tally[vote] = 1;
}
}
foreach (var pair in tally)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
} Whenever the order of the output matters, reach for a SortedDictionary.
guess first
The dice have been rolling. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
string[] rolls = { "six", "two", "six", "six", "four" };
var count = new SortedDictionary<string, int>();
foreach (string roll in rolls)
{
if (count.ContainsKey(roll))
{
count[roll]++;
}
else
{
count[roll] = 1;
}
}
foreach (var pair in count)
{
Console.Write($"{pair.Key}={pair.Value} ");
}
your turn
Your turn. Count the cars going past.
Add two more car colours on line 4. Then finish line 19 so each line shows the colour, a colon and its count, like red: 2.
output
press run to see what happens
fix it
The café tally crashes on the first order. Fix it!
output
press run to see what happens
- C# stops with
KeyNotFoundExceptionon line 8. What is intallythe first time it meets a latte? ++needs a value to add one to, and a brand new key has none yet.- Wrap line 8 in
if (tally.ContainsKey(order)), with anelseblock that setstally[order] = 1;.
nailed it
you can tally anything. :D
- A tally adds one to a key, or starts it at 1.
- Each
pairin a loop has aKeyand aValue. - A
SortedDictionarykeeps its keys in order.
new words in your collection
- tally
- KeyValuePair
- SortedDictionary
This lesson isn’t saved. A free account remembers every lesson you finish.