Dictionary, HashSet and collections review
Lists are queried by position: "give me element 3". But many times you want to search by a name or a key: the price of a product, the phone number of a person, how many times each word appears. For that there is Dictionary<TKey, TValue>, which associates unique keys with values. It is like a real dictionary: you look up a word and get its definition. Lookup by key is very fast even with thousands of entries. Today you will also learn HashSet<T> and close the week with a review of collections.
Creating and using a dictionary
It is declared by indicating the type of the key and of the value: Dictionary<string, decimal> prices. You can initialize it with braces and key-value pairs. To add or change you use the indexer prices["tea"] = 2.5m, which creates the entry if it does not exist and replaces it if it does; the Add method, on the other hand, throws an exception if the key was already there. Reading with prices["coffee"] throws KeyNotFoundException if the key does not exist, so the usual way is TryGetValue, which returns true or false and hands the value through out. ContainsKey asks only about the key, and Remove deletes it.
var prices = new Dictionary<string, decimal>
{
["coffee"] = 2.5m,
["tea"] = 2m,
};
prices["cake"] = 4.75m; // add
prices["tea"] = 2.2m; // replace
if (prices.TryGetValue("coffee", out decimal coffeePrice))
{
Console.WriteLine($"Coffee costs {coffeePrice}"); // Coffee costs 2.5
}
Console.WriteLine(prices.ContainsKey("juice")); // False
Console.WriteLine(prices.Count); // 3
foreach (KeyValuePair<string, decimal> pair in prices)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
prices.Remove("cake");
// prices.Add("tea", 1m); // ArgumentException: key already exists
// Console.WriteLine(prices["juice"]); // KeyNotFoundExceptionA typical case: counting words
Dictionaries are perfect for counting. You go through the elements and, for each one, increase the counter of its key. The technique uses TryGetValue: if the key existed, you start from its counter; if not, from zero. After this, the dictionary stores how many times each word appeared. Note that the traversal order of a dictionary is not something you should rely on; if you need a specific order, sort afterwards with LINQ, which we will see in week 8.
string sentence = "the cat and the dog and the bird";
var counts = new Dictionary<string, int>();
foreach (string word in sentence.Split(' '))
{
counts.TryGetValue(word, out int current); // current is 0 if missing
counts[word] = current + 1;
}
foreach (var (word, count) in counts)
{
Console.WriteLine($"{word} -> {count}");
}
// the -> 3, cat -> 1, and -> 2, dog -> 1, bird -> 1
var unique = new HashSet<string>(sentence.Split(' '));
Console.WriteLine(unique.Count); // 5
Console.WriteLine(unique.Add("cat")); // False: already there
Console.WriteLine(unique.Contains("dog"));// TrueHashSet and how to choose a collection
A HashSet<T> is a set: it stores values without repeating them and checks whether a value exists very quickly with Contains. Add returns false if the value was already there. It is useful for removing duplicates and for remembering "what has been seen". Summary to choose: an array when the size is fixed; a List<T> when order matters and the quantity changes; a Dictionary when you search by a key; a HashSet when only whether something is present matters. Choosing the right collection makes code shorter and faster than forcing a list for everything.
Test what you learned
Question 1 of 6What does prices["x"] do if the key "x" does not exist?
✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters