Learn/C#/13. Dictionaries and sets in depth
Lesson 13 of 15
Sign in

C#, lesson 13

Dictionaries and sets in depth

You met Dictionary<TKey, TValue> in the collections lesson. Dictionaries and sets power a huge number of everyday jobs: counting words, grouping orders by customer, removing duplicates, comparing two lists. This lesson covers the idiomatic way to do each.

Counting

The counting pattern is "read the old count (or 0), add one, store it back". GetValueOrDefault makes it a one-liner:

GetValueOrDefault(key) returns the value if the key exists, or the type's default (0 for int) if it does not, so there is no KeyNotFoundException to worry about.

Grouping

To group items into lists you need "the list for this key, created if missing". does the lookup and the existence check in one step:

2 exercises to try what you just read.

Exercise 1

Top words

Press Ctrl Enter or Check to test your code.

Exercise 2

Club overlap

Press Ctrl Enter or Check to test your code.

TryGetValue

(LINQ's GroupBy, coming in the next lesson, does the same thing in one expression.)

Which dictionary?

TypeOrder when you loopUse it when
Dictionary<K, V>not definedyou mostly look things up (fastest)
SortedDictionary<K, V>sorted by keyyou want sorted output

Give a dictionary or sorted collection a comparer to control how keys match or sort. For example, new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) treats "Apple" and "apple" as the same key, and new SortedDictionary<string, int>(StringComparer.Ordinal) sorts by character code on every computer.

To order a dictionary by its values, sort its entries:

Sets: unique values

A HashSet<T> holds each value at most once and answers Contains very quickly. Add returns false if the value was already there, which makes duplicate detection easy:

SortedSet<T> is the same idea, kept in sorted order, with Min and Max properties.

Set operations

Sets have methods that change the set in place, so start from a copy when you need to keep the originals:

There is also SymmetricExceptWith (in one set or the other, but not both), and the questions IsSubsetOf, IsSupersetOf and Overlaps.

Further reading

  • Dictionary<TKey, TValue>
  • HashSet<T>
  • SortedSet<T>
  • Commonly used collection types

Read all of the input. Split it into words: a word is a run of letters a–z or A–Z; every other character separates words. Ignore case by turning words into lower case. Print the three most frequent words as <word> <count>, most frequent first; break ties in ordinal order. If there are fewer than three distinct words, print them all. If there are no words, print No words.

Hint: walk through each line character by character, building the current word with a StringBuilder, and finish the word whenever you reach a non-letter.

Sample input:

Sample output:

The first line lists the members of the chess club, the second line the members of the drama club (names separated by spaces; a line may be empty, and a name may be repeated by mistake). Using sets, print four lines:

  • Both: followed by the names in both clubs,
  • Chess only: names only in chess,
  • Drama only: names only in drama,
  • Total: the number of different people in at least one club.

List names in ordinal order separated by , . If a list is empty, print - instead.

Sample input:

Sample output:

Dictionary<string, int> counts = new();
foreach (string fruit in new[] { "apple", "pear", "apple" })
{
    counts[fruit] = counts.GetValueOrDefault(fruit) + 1;
}
// apple: 2, pear: 1
Dictionary<char, List<string>> byLetter = new();
foreach (string name in new[] { "ana", "bo", "al", "bea" })
{
    if (!byLetter.TryGetValue(name[0], out var group))
    {
        group = [];
        byLetter[name[0]] = group;
    }
    group.Add(name);
}
// a: [ana, al], b: [bo, bea]
var entries = new List<KeyValuePair<string, int>>(counts);
entries.Sort((a, b) => a.Value != b.Value
    ? b.Value.CompareTo(a.Value)                  // biggest count first
    : string.CompareOrdinal(a.Key, b.Key));       // then by key
HashSet<string> seen = [];
foreach (string word in words)
{
    if (!seen.Add(word)) Console.WriteLine($"Repeated: {word}");
}
var a = new SortedSet<string>(["ana", "bo", "cy"], StringComparer.Ordinal);
var b = new SortedSet<string>(["bo", "cy", "dan"], StringComparer.Ordinal);

var union = new SortedSet<string>(a, StringComparer.Ordinal);
union.UnionWith(b);          // ana, bo, cy, dan

var both = new SortedSet<string>(a, StringComparer.Ordinal);
both.IntersectWith(b);       // bo, cy

var onlyA = new SortedSet<string>(a, StringComparer.Ordinal);
onlyA.ExceptWith(b);         // ana
The cat and the hat.
The CAT sat!
the 3
cat 2
and 1
ana bo cy ana
cy dan bo
Both: bo, cy
Chess only: ana
Drama only: dan
Total: 4