The Analogy: The Storage Wall
A well-run workshop does not keep everything in one big crate. There is a pegboard where every tool hangs in a named silhouette, a drawer unit of small labelled bins, a rack where lengths of timber slide in one end and out the other, and a spike on the bench where receipts pile up newest-on-top. Nobody chose those by what goes in them. They chose by how the thing comes back out.
Collections are that wall. List<T> is the big crate: fine for "keep these in order and let me walk them", hopeless for "do I already have this one?" — a question it can only answer by looking at every item. Dictionary<TKey, TValue> is the pegboard with named silhouettes: it goes straight to the spot. Queue<T> is the timber rack, Stack<T> the receipt spike, SortedSet<T> the drawer that quietly keeps itself alphabetical.
Almost every collection mistake is a container chosen for its contents rather than its access pattern. A List<string> searched with Contains inside a loop over 50,000 items is not slightly slower than a HashSet<string> — it is 50,000 times slower, and it looks completely reasonable on the screen. So the question to ask before declaring one is never "what am I storing?" but "what will I ask of it, and how often?"
Syntax or Core Structure
Six containers, each answering a different question:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Keyed lookup, with a comparer that decides what "same key" means.
var stock = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
["lamp"] = 4,
["desk"] = 2
};
stock["LAMP"] += 1; // same key, different casing
Console.WriteLine(stock.Count + " " + stock["lamp"]);
// Membership only: Add reports whether it was new.
var seen = new HashSet<string> { "a", "b" };
Console.WriteLine(seen.Add("b") + " " + seen.Count);
// First in first out, and last in first out.
var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
var stack = new Stack<string>();
stack.Push("first");
stack.Push("second");
Console.WriteLine(queue.Dequeue() + " / " + stack.Pop());
// Sorted by key at all times, no sort step ever needed.
var sorted = new SortedDictionary<string, int> { ["pear"] = 3, ["apple"] = 9 };
foreach (KeyValuePair<string, int> pair in sorted)
Console.WriteLine(pair.Key + "=" + pair.Value);
// Lowest priority value comes out first.
var jobs = new PriorityQueue<string, int>();
jobs.Enqueue("backup", 5);
jobs.Enqueue("alert", 1);
jobs.Enqueue("report", 3);
Console.WriteLine(jobs.Dequeue() + " then " + jobs.Dequeue());
}
}
Output:
2 5
False 2
first / second
apple=9
pear=3
alert then report
Two lines there are worth a second look. stock["LAMP"] += 1 found the existing lamp entry and left the count at 2, because the comparer handed to the constructor — not the string type — decides key identity. And seen.Add("b") returned False rather than throwing: HashSet<T>.Add is the cheapest "was this new?" test in the framework, so the usual if (!seen.Contains(x)) seen.Add(x) is a redundant lookup.
Technical Depth: Picking by Cost, Not by Habit
The cost table
| Collection | Lookup | Insert | Ordered? | Backed by |
|---|---|---|---|---|
List<T> | O(n) by value, O(1) by index | O(1) amortised at the end | Insertion order | Array |
Dictionary<TKey, TValue> | O(1) average | O(1) average | No guarantee | Buckets plus entry array |
HashSet<T> | O(1) average | O(1) average | No guarantee | Same as Dictionary |
SortedDictionary<TKey, TValue> | O(log n) | O(log n) | By key | Red-black tree |
SortedList<TKey, TValue> | O(log n) | O(n) | By key | Two parallel arrays |
Queue<T> / Stack<T> | Ends only | O(1) amortised | FIFO / LIFO | Array (ring buffer for Queue) |
LinkedList<T> | O(n) | O(1) given the node | Insertion order | Doubly linked nodes |
PriorityQueue<TElement, TPriority> | Peek O(1) | O(log n) | By priority, unstable | Binary heap in an array |
The two sorted dictionaries answer the same question with opposite trade-offs: SortedDictionary inserts cheaply, SortedList uses far less memory and indexes by position. Bulk-load once and read forever, use SortedList; insert continuously, use SortedDictionary.
What a Dictionary actually needs from your key
Dictionary hashes the key to pick a bucket, then walks that bucket comparing with Equals. Two rules follow, and breaking either produces a collection that loses items:
- Equal keys must return equal hash codes. Override
EqualswithoutGetHashCodeand lookups fail for values that compare equal. - A key's hash must not change while it is in the collection. Mutating a field that
GetHashCodereads leaves the entry stranded in the wrong bucket — present inCount, invisible toTryGetValue.
Records and tuples implement both correctly from structural equality, which is why Dictionary<(int, int), T> and Dictionary<MyRecord, T> just work. Mutable classes are the danger: use them as keys only if you leave the hashed fields alone.
Enumeration order is not part of the contract. It happens to follow insertion order until the first removal, which is exactly long enough to write a test that passes and a report that scrambles itself in production. Order explicitly with OrderBy when order matters.
The API that saves the double lookup
Most collection code pays for the same search twice. The framework has a single-pass form of nearly every pattern:
// Two lookups.
if (counts.ContainsKey(path)) counts[path]++; else counts[path] = 1;
// One, and no exception path.
counts[path] = counts.GetValueOrDefault(path) + 1;
// One, when the value is expensive to build.
if (!cache.TryGetValue(id, out Order? order))
cache[id] = order = Load(id);
// Reference into the bucket itself: mutate in place, no rehash (.NET 6+).
ref int slot = ref CollectionsMarshal.GetValueRefOrAddDefault(counts, path, out _);
slot++;
HashSet<T> has its own set algebra — UnionWith, IntersectWith, ExceptWith, IsSubsetOf, Overlaps — all of which beat the LINQ equivalents because they mutate in place instead of building a new sequence.
LinkedList, and the myth of cheap insertion
LinkedList<T> inserts in O(1) if you already hold the node. Finding the node is O(n), each node is a separate heap allocation with two pointers of overhead, and walking it jumps around memory instead of streaming through a cache line. In practice List<T> wins even at insert-in-the-middle for thousands of elements, because Array.Copy is spectacularly fast. Reach for LinkedList<T> when you genuinely keep node references — an LRU cache that moves a known node to the front is the classic honest use.
Immutable and concurrent variants
| Need | Type | Watch out for |
|---|---|---|
| Share a snapshot safely | ImmutableArray<T> | Every mutation copies the whole array |
| Build up immutably | ImmutableList<T> | Tree-backed, O(log n) indexing, slower than it looks |
| Many threads, keyed | ConcurrentDictionary<TKey, TValue> | GetOrAdd may run your factory more than once |
| Producer and consumer | Channel<T> or BlockingCollection<T> | Bound the capacity or memory grows unchecked |
| Hand out a read-only view | IReadOnlyList<T>, AsReadOnly() | A view, not a copy: the source can still change |
ConcurrentDictionary.GetOrAdd deserves its own warning. It is atomic about which value wins, not about how many factories run; two threads racing on a missing key can both build the value. If construction is expensive or has side effects, store a Lazy<T> as the value instead.
Capacity, and the enumerator that does not allocate
Every array-backed collection doubles when it fills, copying as it grows. new List<int>(50_000) or new Dictionary<string, int>(50_000) skips the whole staircase of intermediate arrays. And foreach over a List<T>, Dictionary, Queue or Stack uses a struct enumerator with no allocation at all — until you type the variable as IEnumerable<T>, which boxes it and adds an interface call per element.
Real World Example: Summarising a Request Log
Four questions about one log, each answered by a different container: how many hits per path, which API paths exist, which two endpoints are slowest, and a report in a stable order.
using System;
using System.Collections.Generic;
using System.Linq;
record Hit(string Path, int Milliseconds);
class Program
{
static void Main()
{
Hit[] log =
{
new("/home", 120), new("/api/orders", 340), new("/home", 95),
new("/api/orders", 410), new("/health", 8), new("/api/users", 260),
new("/home", 150), new("/health", 6)
};
// 1. Keyed accumulation: one pass, one lookup per update.
var counts = new Dictionary<string, int>();
var slowest = new Dictionary<string, int>();
foreach (Hit hit in log)
{
counts[hit.Path] = counts.GetValueOrDefault(hit.Path) + 1;
if (hit.Milliseconds > slowest.GetValueOrDefault(hit.Path))
slowest[hit.Path] = hit.Milliseconds;
}
// 2. Membership, no counting: a set, not a list.
var apiPaths = new HashSet<string>(
log.Select(h => h.Path).Where(p => p.StartsWith("/api")));
Console.WriteLine("api paths: " + apiPaths.Count
+ ", orders seen: " + apiPaths.Contains("/api/orders"));
// 3. Top 2 without sorting everything: a heap that never exceeds 2 items.
var top = new PriorityQueue<string, int>();
foreach ((string path, int ms) in slowest)
{
top.Enqueue(path, ms);
if (top.Count > 2) top.Dequeue(); // evict the fastest
}
var winners = new List<string>();
while (top.TryDequeue(out string? path, out int ms))
winners.Add(path + " " + ms + "ms");
winners.Reverse(); // heap yields smallest first
Console.WriteLine("slowest: " + string.Join(", ", winners));
// 4. Report order is stated, never inherited from the Dictionary.
foreach (KeyValuePair<string, int> pair in
counts.OrderByDescending(p => p.Value).ThenBy(p => p.Key))
Console.WriteLine(pair.Key.PadRight(12) + pair.Value);
}
}
Output:
api paths: 2, orders seen: True
slowest: /api/orders 410ms, /api/users 260ms
/home 3
/api/orders 2
/health 2
/api/users 1
The bounded priority queue in step 3 is the part worth stealing. Sorting to take the top 2 costs O(n log n) and touches every element; a heap capped at 2 costs O(n log 2) and holds two items no matter how long the log is. On a million entries that is the difference between an eight-megabyte sort buffer and two strings, which is why "top N of a huge stream" is a heap problem rather than a sort problem.
Step 4 is the discipline the analogy warned about. counts is a pegboard, and a pegboard has no reading order — the entries came out grouped by hash bucket, not by anything a reader would recognise. Every report ends with an explicit OrderBy, and the tie between /health and /api/orders is broken by a stated ThenBy rather than by whichever one happened to hash lower.
Common Mistakes
List<T>.Containsinside a loop. Two nested O(n) scans is O(n squared); the same code with aHashSet<T>is linear. This is the single most common collection performance bug.- Relying on
Dictionaryenumeration order. It is unspecified, and removals reorder it. Sort explicitly, or useSortedDictionaryif order is a requirement rather than a convenience. - Overriding
Equalsbut notGetHashCode. The key hashes to one bucket and its equal twin to another, soAddsucceeds twice andTryGetValuefinds neither. - Mutating a key after inserting it. Change a hashed field and the entry is stranded: still counted, never found. Use records, tuples or immutable keys.
- Indexing with
dictionary[key]for a read. A missing key throwsKeyNotFoundException. UseTryGetValueorGetValueOrDefaultunless absence really is a bug. - Modifying a collection while enumerating it.
InvalidOperationException, even for a removal. Collect the keys first, or iterate a copy, or useRemoveAllon aList<T>. - Assuming
ConcurrentDictionary.GetOrAddruns the factory once. Racing threads can both build the value. Store aLazy<T>when construction is expensive or has side effects. - Treating
AsReadOnly()as a snapshot. It is a live view over the same storage; the owner can still add and remove. UseToArray()or an immutable collection for a real copy.
Best Practices
- Choose by the question you will ask: keyed lookup means
Dictionary, membership meansHashSet, ends-only meansQueueorStack, order-as-you-go means the sorted types. - Pass a comparer rather than normalising keys by hand —
StringComparer.OrdinalIgnoreCasebeats callingToLower()on every key and allocating a string each time. - Presize with a capacity when the final count is roughly known; it removes every intermediate array from a bulk load.
- Prefer the single-pass APIs:
TryGetValue,GetValueOrDefault,HashSet.Add's return value, andTryDequeue. - Use
HashSet's own set operations over the LINQ equivalents when you own the set — they mutate in place instead of allocating a new sequence. - Return
IReadOnlyList<T>orIReadOnlyDictionary<TKey, TValue>from public members, and hand out an immutable collection when the caller must be safe from later edits. - Cap the heap for top-N work instead of sorting the whole sequence;
PriorityQueuewith an eviction step scales to streams that cannot fit in memory. - Reach for
LinkedList<T>only when you hold node references. OtherwiseList<T>wins on both memory and speed, however the complexity table reads.
Practice Exercises
- Load 100,000 random words into both a
List<string>and aHashSet<string>, then look up 10,000 of them in each with aStopwatch. Report both timings and explain the ratio. - Build a word-frequency counter over a paragraph using
GetValueOrDefault, then print the top 5 words with an explicitOrderByDescending(...).ThenBy(...)so ties are stable. - Write a class with mutable
NameandPostcodefields, overrideEqualsandGetHashCodeover both, use one as a dictionary key, then mutateNameand show thatTryGetValueno longer finds it whileCountstill reports 1. - Implement a fixed-size LRU cache using a
Dictionary<TKey, LinkedListNode<TKey>>plus aLinkedList<TKey>for recency, and demonstrate with capacity 3 that the least recently used key is the one evicted.