0Pricing
C# Academy · Lesson

Choosing a Collection

Trade-offs and performance.

Choosing a Collection is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

One Question First

Choosing a collection starts with one question: how will you access the data? By position, by key, or just check membership?

List, Dictionary, and HashSet each answer a different access pattern. Match the tool to the pattern and your code stays fast and clear.

Access by Position: List

If order matters and you reach items by index, choose List<T>. It keeps insertion order and gives O(1) indexing.

Examples: a queue of steps, rows in display order, or any sequence you iterate front to back. Duplicates are allowed.

var steps = new List<string> { "mix", "bake", "cool" };
string first = steps[0]; // O(1) by index

Access by Key: Dictionary

If you look things up by a unique identifier, choose Dictionary<K,V>. It maps key to value in average O(1).

Examples: user id to user, country code to name, word to its count. The key answers "which one", the value carries the data.

var users = new Dictionary<int, string> {
    [101] = "Ann",
    [102] = "Bob"
};
string name = users[101];

Membership and Uniqueness: HashSet

If you only care whether a value is present, or you must reject duplicates, choose HashSet<T>. Contains is average O(1).

Examples: visited URLs, allowed permissions, distinct tags. There is no value attached, just the presence of the element.

var visited = new HashSet<string>();
if (visited.Add(url)) {
    // first time seeing this url
}

The Cost Table

Average costs: List indexing O(1), but Contains O(n). Dictionary and HashSet lookup O(1).

List.Add at the end is amortized O(1); inserting or removing in the middle is O(n). Dictionary and HashSet add and remove are average O(1).

// List:       index O(1),  Contains O(n)
// Dictionary: by-key O(1), no index
// HashSet:    Contains O(1), no value, no index

List Contains Is a Smell

Repeatedly calling list.Contains inside a loop is an O(n squared) trap. Each check scans the whole list.

If membership checks dominate, switch to a HashSet. The single change can turn a sluggish loop into an instant one on large data.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var allow = new HashSet<int> { 2, 4, 6 };
        foreach (int n in new[] { 1, 2, 3, 4 })
            if (allow.Contains(n)) Console.Write(n + " ");
    }
}

When You Need Both Key and Order

Need key lookup but also predictable order? Standard Dictionary does not guarantee order.

Consider keeping a List for order alongside a Dictionary for lookup, or use SortedDictionary<K,V> for keys kept in sorted order at O(log n) cost.

var sorted = new SortedDictionary<string, int>();
sorted["b"] = 2;
sorted["a"] = 1;
// enumerates a then b, in key order

Memory Trade-offs

Hash-based collections trade memory for speed. Dictionary and HashSet keep internal buckets, using more memory than a tight List or array.

For small collections of a handful of items, a List scan can actually be fine and uses less memory. Hashing pays off at scale.

Program to Interfaces

Method signatures should ask for the least specific type that works. Accept IEnumerable<T> to read, IReadOnlyList<T> for indexed reads, IDictionary<K,V> for key access.

This decouples callers from your concrete choice, letting you swap implementations later without breaking signatures.

int Sum(IEnumerable<int> values) {
    int total = 0;
    foreach (int v in values) total += v;
    return total;
}

A Worked Example

Counting unique words in text uses two collections together. A HashSet tracks seen words; a Dictionary tallies counts.

Each does one job well: the set enforces uniqueness, the dictionary maps word to frequency, both in average O(1) per operation.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var counts = new Dictionary<string, int>();
        foreach (var w in "a b a c b a".Split(' '))
            counts[w] = counts.GetValueOrDefault(w) + 1;
        Console.WriteLine(counts["a"]); // 3
    }
}

Decision Checklist

Ask in order: Do I need a key-to-value map? Use Dictionary. Do I only need uniqueness or membership? Use HashSet.

Otherwise, do I need order and index access, possibly with duplicates? Use List. This short checklist covers most everyday cases.

Quick Check

Apply the decision checklist to a concrete need.

Recap

Pick by access pattern: List for ordered, indexed sequences; Dictionary for key-to-value lookup; HashSet for uniqueness and membership.

Watch the Big-O: avoid List.Contains in hot loops, lean on O(1) hash lookups, and program to interfaces so your choice stays flexible.

Frequently asked questions

Is the “Choosing a Collection” lesson free?

Yes — the full text of “Choosing a Collection” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Choosing a Collection”?

Trade-offs and performance. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Choosing a Collection” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. List in Practice
  2. Dictionary Lookups
  3. HashSet and Uniqueness
  4. Choosing a Collection
← Back to C# Academy