Lists & Dictionaries: The Modern Toolbox

Lists & Dictionaries: The Modern Toolbox in C#: Last lesson's array was a locker room: a fixed wall of numbered doors, decided the day the building went up.

The Analogy: The Rack and the Labelled Drawers

Last lesson's array was a locker room: a fixed wall of numbered doors, decided the day the building went up. The workshop you actually work in has two better fittings.

The first is a tool rack that grows. Tools hang in order, you can point at "the third one", and when you buy a fourth the rack simply gets longer — no rebuilding the wall. That is List<T>.

The second is a cabinet of labelled drawers. You never count drawers to find the 3mm bits; you read the labels and go straight there. Adding a label is instant, and finding one takes the same time whether the cabinet holds ten drawers or ten million. That is Dictionary<TKey, TValue>.

Nearly every collection decision in C# is: do I look things up by position, or by name? Rack, or drawers.


Syntax or Core Structure

using System;
using System.Collections.Generic;

class Program
{
    static int Sum(IEnumerable<int> xs)
    {
        int total = 0;
        foreach (int x in xs) total += x;
        return total;
    }

    static void Main()
    {
        List<string> queue = new() { "ada", "grace" };     // target-typed new
        queue.Add("alan");                                 // to the end
        queue.Insert(0, "linus");                          // to the front
        queue.Remove("grace");                             // by value, not position

        Console.WriteLine($"{queue.Count} waiting: {string.Join(" -> ", queue)}");
        Console.WriteLine($"first {queue[0]}, last {queue[^1]}, has ada: {queue.Contains("ada")}");

        Dictionary<string, int> stock = new()
        {
            ["mug"] = 12,
            ["tee"] = 3
        };
        stock["hat"] = 7;          // the indexer inserts when the key is new...
        stock["mug"] += 5;         // ...and updates when it is not

        if (stock.TryGetValue("tee", out int tees))
            Console.WriteLine($"tees: {tees}");

        Console.WriteLine($"scarves: {(stock.TryGetValue("scarf", out int n) ? n.ToString() : "not stocked")}");

        List<string> names = new(stock.Keys);   // dictionary order is not guaranteed,
        names.Sort();                           // so take the keys and sort them

        foreach (string name in names)
            Console.WriteLine($"  {name,-5} {stock[name],3}");

        Console.WriteLine($"{stock.Count} lines, {Sum(stock.Values)} items");
    }
}

Output:

3 waiting: linus -> ada -> alan
first linus, last alan, has ada: True
tees: 3
scarves: not stocked
  hat      7
  mug     17
  tee      3
3 lines, 27 items

Three things worth noticing. Remove("grace") searched by value — the list has no idea where "grace" was until it looks. stock["mug"] += 5 needed no "does this key exist" ceremony because the key did exist. And TryGetValue is how you ask a dictionary a question that might have no answer, without an exception and without looking twice.


Technical Depth: What Is Underneath

List<T> is an array that lies about its size

Inside every List<T> is a plain T[]. Count is how many slots you have filled; Capacity is how long the array actually is. When Add runs out of room the list allocates a new array of double the capacity, copies everything across and throws the old one away:

var xs = new List<int>();
Console.WriteLine($"{xs.Count}/{xs.Capacity}");   // 0/0
xs.Add(1);
Console.WriteLine($"{xs.Count}/{xs.Capacity}");   // 1/4
for (int i = 0; i < 4; i++) xs.Add(i);
Console.WriteLine($"{xs.Count}/{xs.Capacity}");   // 5/8

var sized = new List<int>(1000);                  // one allocation, no copying

Doubling is why Add is amortised O(1) rather than genuinely constant, and why passing a known size to the constructor is free performance when you are loading ten thousand rows.

The cost table you should carry in your head

OperationList<T>Dictionary<K,V>HashSet<T>
Read by index / keyO(1)O(1) averagen/a
Add at the end / insertO(1) amortisedO(1) averageO(1) average
Insert or remove in the middleO(n) — shifts everythingO(1) averageO(1) average
ContainsO(n) — scansO(1) average (ContainsKey)O(1) average
Ordered when enumeratedYes, insertion orderNo guaranteeNo guarantee
Duplicates allowedYesKeys no, values yesNo

That third row is the one that bites. Removing items one at a time from the front of a 100,000-element list is a hundred thousand shifts of a hundred thousand elements. And the fourth row is why list.Contains(x) inside a loop over another list is the most common accidental O(n²) in C#: put one side in a HashSet<T> and it collapses to O(n).

Choosing the right container

You needUse
Ordered, indexable, growableList<T>
Lookup by keyDictionary<TKey, TValue>
Membership only, no duplicatesHashSet<T>
First in, first outQueue<T> (Enqueue / Dequeue)
Last in, first outStack<T> (Push / Pop)
Keys always sortedSortedDictionary<K,V> (O(log n)) or SortedList<K,V>
Cheap inserts anywhere, no indexingLinkedList<T> (rarely the right answer)
A snapshot nobody can changeImmutableArray<T>, or IReadOnlyList<T> over a private list

Dictionary keys live and die by GetHashCode

A dictionary finds a key by hashing it, so a key type must give equal objects equal hash codes. string, int, enum, tuples and records all do this correctly out of the box. A hand-written class does not unless you override Equals and GetHashCode — otherwise two "identical" keys are different objects and your lookup silently misses.

Worse, a mutable key can lose itself:

var tags = new Dictionary<List<int>, string>();
var key = new List<int> { 1 };
tags[key] = "first";
key.Add(2);                        // the object moved... or did it?

List<T> hashes by reference so this one survives, but any type that hashes by content will hash to a different bucket after mutation and the entry becomes unreachable. Use immutable keys.

Reading a key that may not be there

int a = stock["scarf"];                                 // KeyNotFoundException
int b = stock.TryGetValue("scarf", out int v) ? v : 0;   // one lookup, safe
int c = stock.GetValueOrDefault("scarf", 0);             // same, shorter
if (stock.ContainsKey("scarf")) { int d = stock["scarf"]; }   // two lookups: wasteful

The "count occurrences" idiom is worth memorising, because += 1 works on a missing key once the default is filled in:

counts[word] = counts.GetValueOrDefault(word) + 1;

You may not edit a collection you are walking

foreach (string name in queue)
    if (name.Length < 4) queue.Remove(name);      // InvalidOperationException

The enumerator notices the collection changed underneath it and refuses. Three fixes: queue.RemoveAll(name => name.Length < 4); (the good one), loop backwards by index, or iterate a copy — foreach (string name in new List<string>(queue)).

Structs in lists surprise people

List<T>'s indexer returns a copy for value types, so mutating it is meaningless — and the compiler says so:

struct Point { public int X; }
var pts = new List<Point> { new Point() };
// pts[0].X = 5;              // CS1747 / CS1612: cannot modify the return value
Point p = pts[0]; p.X = 5; pts[0] = p;    // read, change, write back

Arrays do allow arr[0].X = 5, because an array element is a real storage location and a list's indexer is a method. One more reason to prefer readonly record struct for small values.

Expose the interface, not the field

Hand out IReadOnlyList<T> or IReadOnlyDictionary<K,V> from public properties, keeping the mutable List<T> private. Callers can read and foreach; they cannot Add behind your back. That is the pattern MemoryLog.Entries used in the interfaces lesson.


Real World Example: The Triage Board

A support board needs all four containers at once: tickets grouped by key (dictionary), each group ordered (list), reporters counted without duplicates (hash set), and urgent items handled in arrival order (queue).

using System;
using System.Collections.Generic;

// a record: the compact class form covered in Module 8
record Ticket(int Id, string Team, string Reporter, int Severity, string Title);

class TriageBoard
{
    private readonly Dictionary<string, List<Ticket>> byTeam = new();
    private readonly HashSet<string> reporters = new();
    private readonly Queue<Ticket> urgent = new();

    public void Add(Ticket t)
    {
        if (!byTeam.TryGetValue(t.Team, out List<Ticket>? bucket))
        {
            bucket = new List<Ticket>();      // first ticket for this team
            byTeam[t.Team] = bucket;
        }
        bucket.Add(t);

        reporters.Add(t.Reporter);            // returns false for a repeat; we do not care
        if (t.Severity == 1) urgent.Enqueue(t);
    }

    public void Print()
    {
        List<string> teams = new(byTeam.Keys);
        teams.Sort();

        foreach (string team in teams)
        {
            List<Ticket> bucket = byTeam[team];
            bucket.Sort((a, b) => a.Severity.CompareTo(b.Severity));

            Console.WriteLine($"{team} ({bucket.Count})");
            foreach (Ticket t in bucket)
                Console.WriteLine($"   S{t.Severity} #{t.Id,-4} {t.Title}");
        }

        Console.WriteLine($"{reporters.Count} distinct reporters, {urgent.Count} urgent queued");

        while (urgent.Count > 0)                       // FIFO: oldest emergency first
        {
            Ticket t = urgent.Dequeue();
            Console.WriteLine($"   paging {t.Team} for #{t.Id}");
        }
    }
}

class Program
{
    static void Main()
    {
        var board = new TriageBoard();
        board.Add(new Ticket(101, "payments", "ada",   2, "refund stuck"));
        board.Add(new Ticket(102, "search",   "grace", 1, "index offline"));
        board.Add(new Ticket(103, "payments", "ada",   1, "double charge"));
        board.Add(new Ticket(104, "search",   "alan",  3, "typo in facet"));
        board.Add(new Ticket(105, "payments", "grace", 3, "slow settlement"));

        board.Print();
    }
}

Output:

payments (3)
   S1 #103  double charge
   S2 #101  refund stuck
   S3 #105  slow settlement
search (2)
   S1 #102  index offline
   S3 #104  typo in facet
3 distinct reporters, 2 urgent queued
   paging search for #102
   paging payments for #103

Five Add calls, three reporters: ada and grace each filed twice and the hash set collapsed them for free. The queue pages search before payments because ticket 102 arrived first — arrival order the dictionary could never have told you. And the "get the bucket or create it" block at the top of Add is the single most-typed dictionary idiom in C#; commit it to muscle memory.


Common Mistakes

  1. list.Contains(x) inside a loop over another list. Two 10,000-item lists means 100,000,000 comparisons. Build a HashSet<T> from one side first.
  2. Reading a dictionary with the indexer when the key might be absent. stock["scarf"] throws KeyNotFoundException; use TryGetValue or GetValueOrDefault.
  3. ContainsKey followed by the indexer. Correct but it hashes the key twice. TryGetValue does it once.
  4. Adding or removing during foreach. InvalidOperationException, every time. Use RemoveAll, a backwards for, or a copy.
  5. Relying on dictionary or HashSet enumeration order. It is unspecified, it has changed between runtimes, and code that depends on it breaks quietly. Sort the keys if order matters.
  6. Using a mutable class as a dictionary key, or one that overrides Equals but not GetHashCode. Lookups will miss for reasons that look like magic.
  7. Remove when you meant RemoveAt. ints.Remove(2) deletes the value 2; ints.RemoveAt(2) deletes the third element. With a List<int> both compile.
  8. Exposing public List<T> Items { get; }. Every caller can now mutate your internals. Return IReadOnlyList<T> and keep the list private.

Best Practices

  • Default to List<T> for sequences and Dictionary<K,V> for lookups, and only reach past them when a measurement or an obvious access pattern says otherwise.
  • Pre-size when you know the size: new List<T>(rows.Count) and new Dictionary<string,int>(1024) skip all the doubling and copying.
  • Prefer TryGetValue over ContainsKey + indexer, and GetValueOrDefault for the "count occurrences" idiom.
  • Reach for HashSet<T> the moment you catch yourself asking "have I seen this before?" — deduplication and membership are what it exists for.
  • Use immutable key types: string, int, enum, a tuple, or a record. Never a class you plan to mutate.
  • Use RemoveAll with a predicate rather than hand-rolling a removal loop; it does one pass and cannot throw the modification exception.
  • Return IReadOnlyList<T> / IReadOnlyDictionary<K,V> from public members, keeping the concrete collection private.
  • Group with Dictionary<TKey, List<TValue>> and remember the get-or-create idiom — or let LINQ's GroupBy do it for you, which is exactly where the next lesson starts.

Practice Exercises

  1. Build a List<string> of ten shopping items with three duplicates. Print the count, then produce a duplicate-free List<string> using a HashSet<string> to decide what to keep, and print how many were dropped.
  2. Write static Dictionary<char, int> LetterCounts(string text) that counts letters case-insensitively, ignoring anything that is not a letter, using the GetValueOrDefault idiom. Print the results with the keys sorted, and state the most frequent letter.
  3. Model a print spooler with a Queue<string> and an undo history with a Stack<string>. Enqueue five jobs, process three (pushing each onto the stack as it completes), then pop two off the stack and report what "un-printing" them would mean. Print Count for both containers at each stage.
  4. Take the TriageBoard and add bool Close(int id) that finds and removes a ticket by id from whichever team holds it, deleting the team's entry entirely when its list becomes empty. Prove it works by closing ticket 104 and printing the board again, and explain in a comment why you must not remove from byTeam while iterating it.