×

c# · level 2 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.