Collections and equality
Picking the right collection decides whether a job takes milliseconds or seconds. HashSet and Dictionary give average O(1) lookups through hashing, but only if the key type implements Equals and GetHashCode correctly and stays immutable.
29.1 Why is it used?
- List.Contains scans item by item (O(n)); inside a loop of n items the total becomes O(n²).
- For 50,000 IDs that is about 1.25 billion comparisons.
- Hash-based collections jump straight to a bucket instead of scanning.
- Queue, Stack and PriorityQueue model order of processing: arrival, last-in, or importance.
29.2 The bug: a 20 second loop
C#
using System.Diagnostics; var seen = new List<string>();var timer = Stopwatch.StartNew();for (int i = 0; i < 50_000; i++){ string id = $"ORD-{i}"; if (!seen.Contains(id)) seen.Add(id);}Console.WriteLine($"{seen.Count} unique orders");Console.WriteLine( $"Time: {timer.ElapsedMilliseconds} ms");Output
$ dotnet run Dedupe.cs50000 unique ordersTime: 19424 ms29.3 Fix: HashSet
- HashSet keeps only unique items.
- Add returns false if the item already exists, so no separate Contains check is needed.
C#
using System.Diagnostics; var seen = new HashSet<string>();var timer = Stopwatch.StartNew();for (int i = 0; i < 50_000; i++){ string id = $"ORD-{i}"; seen.Add(id);}Console.WriteLine($"{seen.Count} unique orders");Console.WriteLine( $"Time: {timer.ElapsedMilliseconds} ms");Output
$ dotnet run Dedupe.cs50000 unique ordersTime: 56 ms- Step 1
1.GetHashCode turns the item into a number
- Step 2
2.That number picks a bucket directly (no scan)
- Step 3
3.Equals checks the small group in that bucket for an exact match
- Step 4
4.Match found: average O(1) lookup
Dictionary keys work the same way
29.4 Dictionary: key to value
C#
var stock = new Dictionary<string, int>{ ["MIXER-01"] = 3, ["KETTLE-02"] = 0,};stock["TOASTER-03"] = 7;stock["MIXER-01"] -= 1; if (stock.TryGetValue("FAN-04", out int qty)) Console.WriteLine($"FAN-04: {qty}");else Console.WriteLine("FAN-04 not in stock list"); Console.WriteLine(stock["MIXER-01"]);Console.WriteLine($"Items: {stock.Count}");Output
$ dotnet run Stock.csFAN-04 not in stock list2Items: 3- stock[key] = value adds or updates.
- TryGetValue returns false for a missing key instead of throwing KeyNotFoundException like stock[key] does on read.
29.5 Equality: a class as the key
C#
var stock = new Dictionary<SkuKey, int>();stock[new SkuKey("TSHIRT", "M")] = 5; var key = new SkuKey("TSHIRT", "M");Console.WriteLine(stock.ContainsKey(key));stock[key] = 2;Console.WriteLine(stock.Count); class SkuKey(string code, string size){ public string Code { get; } = code; public string Size { get; } = size;}Output
$ dotnet run SkuKey.csFalse2- A class compares references by default, so two objects with the same values get different hash codes.
- The same T-shirt got stored twice.
- Fix: a record generates Equals and GetHashCode from the values.
C#
record SkuKey(string Code, string Size);Output
$ dotnet run SkuKey.csTrue129.6 Checkpoint: what if the key changes?
C#
var cart = new HashSet<CartItem>();var item = new CartItem { Sku = "MIXER-01" };cart.Add(item); item.Sku = "KETTLE-02";Console.WriteLine(cart.Contains(item));Console.WriteLine(cart.Count); record CartItem{ public string Sku { get; set; } = "";}Output
$ dotnet run MutableKey.csFalse1The new Sku gives a new hash code, so the HashSet looks in the wrong bucket. The item is still inside but cannot be found: keep keys immutable.
29.7 Queue, Stack and PriorityQueue
C#
var orders = new Queue<string>();orders.Enqueue("ORD-1");orders.Enqueue("ORD-2");orders.Enqueue("ORD-3");Console.WriteLine(orders.Dequeue());Console.WriteLine(orders.Peek()); var history = new Stack<string>();history.Push("Home");history.Push("Mobiles");history.Push("Product page");Console.WriteLine(history.Pop());Console.WriteLine(history.Peek());Output
$ dotnet run QueueStack.csORD-1ORD-2Product pageMobiles- Queue: first in, first out, like a ticket counter line.
- Stack: last in, first out, like the browser back button.
- PriorityQueue<TElement, TPriority>: the smallest priority number comes out first.
C#
var tickets = new PriorityQueue<string, int>();tickets.Enqueue("Refund pending", 2);tickets.Enqueue("Payment failed", 1);tickets.Enqueue("Change address", 3);tickets.Enqueue("Account hacked", 0); while (tickets.TryDequeue(out var t, out int p)) Console.WriteLine($"P{p}: {t}");Output
$ dotnet run Tickets.csP0: Account hackedP1: Payment failedP2: Refund pendingP3: Change address29.8 Big-O table
| Collection | Main operations | Cost | Use for |
|---|---|---|---|
| List<T> | Index get / Contains | O(1) / O(n) | Ordered items, access by index |
| Dictionary<TKey,TValue> | Add, remove, lookup by key | O(1) average | Key to value (stock per SKU) |
| HashSet<T> | Add, remove, Contains | O(1) average | Unique items, fast membership |
| Queue<T> | Enqueue / Dequeue | O(1) | FIFO processing |
| Stack<T> | Push / Pop | O(1) | LIFO, undo / back |
| PriorityQueue<T,P> | Enqueue / Dequeue | O(log n) | Process by importance |
29.9 Sorting: IComparable vs IComparer
- If a type defines no order, List.Sort throws InvalidOperationException ("At least one object must implement IComparable").
- IComparable<T> gives the type its one natural order (here by price).
- IComparer<T> keeps extra orders in a separate class; Comparer<T>.Create builds one from a lambda.
C#
List<Product> products = [new("Kettle", 1299m, 4.1), new("Mixer", 3499m, 4.6), new("Toaster", 899m, 3.9)];products.Sort();foreach (var p in products) Console.WriteLine($"{p.Name} {p.Price}"); record Product(string Name, decimal Price, double Rating) : IComparable<Product>{ public int CompareTo(Product? other) => other is null ? 1 : Price.CompareTo(other.Price);}Output
$ dotnet run Sort.csToaster 899Kettle 1299Mixer 3499C#
products.Sort(new ByRatingDesc());foreach (var p in products) Console.WriteLine($"{p.Name} {p.Rating}"); products.Sort(Comparer<Product>.Create( (a, b) => b.Price.CompareTo(a.Price)));Console.WriteLine(products[0].Name); class ByRatingDesc : IComparer<Product>{ public int Compare(Product? x, Product? y) => y!.Rating.CompareTo(x!.Rating);}Output
$ dotnet run Comparer.csMixer 4.6Kettle 4.1Toaster 3.9Mixer| Point | IComparable<T> | IComparer<T> |
|---|---|---|
| Where | Implemented by the type itself | Separate class or Comparer<T>.Create |
| Method | CompareTo(other) | Compare(x, y) |
| How many orders | One natural order | As many as you need |
| Call | list.Sort() | list.Sort(comparer) |
29.10 Common mistakes
- Removing from a List inside foreach: InvalidOperationException, collection was modified. Use cart.RemoveAll(l => l.Qty == 0) (returns the count removed: Removed 2, Left 1).
- Using a class without Equals/GetHashCode as a Dictionary key.
- Changing a key after adding it to a HashSet or Dictionary.
- Myth: Dictionary/HashSet are always O(1). If every object returns the same hash code, all go into one bucket and lookups become O(n). Use HashCode.Combine or a record.
29.11 Rules
- For repeated lookups use HashSet or Dictionary, not List.
- Key types: a record, or override Equals and GetHashCode together.
- Keep keys immutable.
- Use TryGetValue for keys that may be missing.
- Natural order with IComparable, extra orders with IComparer.
29.12 Interview tips
- A Dictionary picks a bucket with GetHashCode, then matches the exact key with Equals.
- Equal objects must return the same hash code, or lookups fail; use immutable records as keys.
- List.Contains is O(n); HashSet/Dictionary are O(1) average; PriorityQueue is O(log n).
- IComparable = the type's natural order; IComparer = external, extra orders.