Collections: Dictionary, HashSet, Queue and Stack
Learn Dictionary, HashSet, SortedDictionary, Queue and Stack, when each one fits, and count words in a text with results verified against Python.
In this lesson you will
- Use Dictionary and HashSet
- Count items with a dictionary
- Use Queue and Stack
- Pick the right collection
About 28 minutes
Which items sell the most?
Omar wants to know how often each item appears in a day’s orders, which items appear at all, and he wants to serve orders in the order they arrived. A List answers none of these well. The generic collections in System.Collections.Generic each answer a different question, and choosing well makes programs both simpler and faster.
| Collection | Holds | Duplicates | Best for |
|---|---|---|---|
| List | A sequence | Allowed | An ordered list that grows |
| HashSet | Distinct values | No | Membership tests, removing duplicates |
| Dictionary | Key to value pairs | Unique keys | Fast lookup by key, counting |
| SortedDictionary | Pairs sorted by key | Unique keys | Reports in key order |
| Queue | First in, first out | Allowed | Serving in arrival order |
| Stack | Last in, first out | Allowed | Undo, backtracking |
A dictionary finds a key by computing its hash code, so the cost of a lookup stays about the same however many items it holds. Keys must have consistent Equals and GetHashCode, which strings, numbers and records already have. Asking for a missing key with the indexer throws a KeyNotFoundException, so you either test with ContainsKey or use TryGetValue, which returns a flag and the value. The iteration order of a Dictionary is not something to rely on, so when order matters use SortedDictionary or sort the results explicitly.
string text = "latte tea latte cake latte tea mocha latte tea cake";
var words = text.Split(' ');
Console.WriteLine($"orders: {words.Length}, first: {words[0]}");
var distinct = new HashSet<string>(words);
Console.WriteLine($"distinct items: {distinct.Count}");
var counts = new Dictionary<string, int>();
foreach (var w in words)
{
counts.TryGetValue(w, out int c);
counts[w] = c + 1;
}
var sorted = new SortedDictionary<string, int>(counts);
Console.WriteLine("sorted: " + string.Join(", ", sorted.Select(kv => $"{kv.Key}={kv.Value}")));
var top = counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key).First();
Console.WriteLine($"most ordered: {top.Key} ({top.Value} times)");
Console.WriteLine($"has mocha: {counts.ContainsKey("mocha")}, has soup: {counts.ContainsKey("soup")}, TryGetValue soup: {counts.TryGetValue("soup", out int soup)} -> {soup}");
try { Console.WriteLine(counts["soup"]); }
catch (KeyNotFoundException) { Console.WriteLine("KeyNotFoundException for a missing key"); }
var queue = new Queue<string>(new[] { "Ana", "Ben", "Cy" });
Console.WriteLine($"served first: {queue.Dequeue()}, next: {queue.Peek()}, waiting: {queue.Count}");
var undo = new Stack<string>();
undo.Push("add tea"); undo.Push("add cake"); undo.Push("remove tea");
Console.WriteLine($"undo last action: {undo.Pop()}, then: {undo.Pop()}, left: {undo.Count}");
orders: 10, first: latte
distinct items: 4
sorted: cake=2, latte=4, mocha=1, tea=3
most ordered: latte (4 times)
has mocha: True, has soup: False, TryGetValue soup: False -> 0
KeyNotFoundException for a missing key
served first: Ana, next: Ben, waiting: 2
undo last action: remove tea, then: add cake, left: 1
The text held 10 orders, and the HashSet reduced them to 4 distinct items. The dictionary counted each one by reading the current count with TryGetValue, which leaves zero when the key is missing, and storing the count plus one. The SortedDictionary printed the counts in alphabetical order: cake=2, latte=4, mocha=1, tea=3. The most ordered item was latte, with 4 orders, and the ordering of the LINQ query broke the tie by name so that the result is the same on every machine. The indexer threw a KeyNotFoundException for the missing key, which is why TryGetValue and ContainsKey exist.
The queue served Ana first, since it arrived first, and then Ben was next with 2 still waiting. The stack worked the opposite way: the last action added was the first one undone, “remove tea”, then “add cake”, leaving 1. Choosing between a queue and a stack is choosing between fairness and undo, and getting it wrong is a classic mistake.
Check by hand: latte appears 4 times, tea 3 times, cake 2 times and mocha once, which adds to 10. Python’s collections.Counter on the same words gave {‘cake’: 2, ‘latte’: 4, ‘mocha’: 1, ‘tea’: 3}, identical to the dictionary result.
Choosing in practice
A helpful way to choose is to ask which question you will put to the collection most often. If it is “what is item number i”, you want a list or an array. If it is “have I seen this before”, you want a set. If it is “what belongs to this key”, you want a dictionary. If it is “who is next”, you want a queue. Asking the question first stops you from reaching for List every time, which works but makes membership tests slow on large data, since a list must look at every element while a hash-based collection jumps straight to the answer.
The enumeration order of a Dictionary is an implementation detail. Use SortedDictionary or sort the results when order matters.
One call both checks and reads the value, instead of ContainsKey followed by the indexer, which looks the key up twice.
Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8.
Practice
Count the words in a paragraph you write, ignoring case, and print the three most common. Use a HashSet to find the words that appear in one text but not in another. Decide which collection suits a to-do list that must be processed in order.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Which collection removes duplicates?
- List
- Array
- HashSet
- Queue
A set holds distinct values.
What does TryGetValue return?
- The value or throws
- A flag, and the value through an out parameter
- Only the key
- A list
No exception for a missing key.
Which collection serves items in arrival order?
- Stack
- Queue
- HashSet
- Array
First in, first out.
What does a Stack do?
- Returns the most recent item first
- Returns the oldest first
- Sorts items
- Removes duplicates
Last in, first out.
Why break ties by name in the query?
- To make the result the same on every run
- To make it faster
- Because C# requires it
- To remove items
Dictionary order is not defined.
Summary
- List keeps order; HashSet holds distinct values; Dictionary maps keys to values.
- Use TryGetValue to read safely.
- Queue is first in first out; Stack is last in first out.
- Sort when order matters.
Questions
When should I use an array instead of a List?
When the size is fixed and you want the simplest, fastest container. Use List otherwise.
What are generics?
A way to say what type a collection holds so the compiler checks it, such as List<string>.
Are these collections thread-safe?
No. For use from several threads, the System.Collections.Concurrent namespace has safe versions.
