Advanced Collections: Choosing the Container

Advanced Collections: Choosing the Container in C#: A well-run workshop does not keep everything in one big crate.

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

CollectionLookupInsertOrdered?Backed by
List<T>O(n) by value, O(1) by indexO(1) amortised at the endInsertion orderArray
Dictionary<TKey, TValue>O(1) averageO(1) averageNo guaranteeBuckets plus entry array
HashSet<T>O(1) averageO(1) averageNo guaranteeSame as Dictionary
SortedDictionary<TKey, TValue>O(log n)O(log n)By keyRed-black tree
SortedList<TKey, TValue>O(log n)O(n)By keyTwo parallel arrays
Queue<T> / Stack<T>Ends onlyO(1) amortisedFIFO / LIFOArray (ring buffer for Queue)
LinkedList<T>O(n)O(1) given the nodeInsertion orderDoubly linked nodes
PriorityQueue<TElement, TPriority>Peek O(1)O(log n)By priority, unstableBinary 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 Equals without GetHashCode and lookups fail for values that compare equal.
  • A key's hash must not change while it is in the collection. Mutating a field that GetHashCode reads leaves the entry stranded in the wrong bucket — present in Count, invisible to TryGetValue.

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

NeedTypeWatch out for
Share a snapshot safelyImmutableArray<T>Every mutation copies the whole array
Build up immutablyImmutableList<T>Tree-backed, O(log n) indexing, slower than it looks
Many threads, keyedConcurrentDictionary<TKey, TValue>GetOrAdd may run your factory more than once
Producer and consumerChannel<T> or BlockingCollection<T>Bound the capacity or memory grows unchecked
Hand out a read-only viewIReadOnlyList<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

  1. List<T>.Contains inside a loop. Two nested O(n) scans is O(n squared); the same code with a HashSet<T> is linear. This is the single most common collection performance bug.
  2. Relying on Dictionary enumeration order. It is unspecified, and removals reorder it. Sort explicitly, or use SortedDictionary if order is a requirement rather than a convenience.
  3. Overriding Equals but not GetHashCode. The key hashes to one bucket and its equal twin to another, so Add succeeds twice and TryGetValue finds neither.
  4. 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.
  5. Indexing with dictionary[key] for a read. A missing key throws KeyNotFoundException. Use TryGetValue or GetValueOrDefault unless absence really is a bug.
  6. Modifying a collection while enumerating it. InvalidOperationException, even for a removal. Collect the keys first, or iterate a copy, or use RemoveAll on a List<T>.
  7. Assuming ConcurrentDictionary.GetOrAdd runs the factory once. Racing threads can both build the value. Store a Lazy<T> when construction is expensive or has side effects.
  8. Treating AsReadOnly() as a snapshot. It is a live view over the same storage; the owner can still add and remove. Use ToArray() or an immutable collection for a real copy.

Best Practices

  • Choose by the question you will ask: keyed lookup means Dictionary, membership means HashSet, ends-only means Queue or Stack, order-as-you-go means the sorted types.
  • Pass a comparer rather than normalising keys by hand — StringComparer.OrdinalIgnoreCase beats calling ToLower() 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, and TryDequeue.
  • 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> or IReadOnlyDictionary<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; PriorityQueue with an eviction step scales to streams that cannot fit in memory.
  • Reach for LinkedList<T> only when you hold node references. Otherwise List<T> wins on both memory and speed, however the complexity table reads.

Practice Exercises

  1. Load 100,000 random words into both a List<string> and a HashSet<string>, then look up 10,000 of them in each with a Stopwatch. Report both timings and explain the ratio.
  2. Build a word-frequency counter over a paragraph using GetValueOrDefault, then print the top 5 words with an explicit OrderByDescending(...).ThenBy(...) so ties are stable.
  3. Write a class with mutable Name and Postcode fields, override Equals and GetHashCode over both, use one as a dictionary key, then mutate Name and show that TryGetValue no longer finds it while Count still reports 1.
  4. Implement a fixed-size LRU cache using a Dictionary<TKey, LinkedListNode<TKey>> plus a LinkedList<TKey> for recency, and demonstrate with capacity 3 that the least recently used key is the one evicted.