C# › Collections

What is the difference between Dictionary<TKey, TValue> and List<T> in terms of lookup performance?

Beginner

Answer

Dictionary<TKey, TValue> provides average O(1) constant-time lookups by key via hashing; List<T> requires an O(n) linear scan to find an element unless you already know its exact index — Dictionary is the right choice whenever you need fast lookups by a unique identifier.
Dictionary<string, int> ages = new() { ["Sam"] = 30, ["Alex"] = 25 };
int samAge = ages["Sam"]; // O(1) lookup

List<(string Name, int Age)> list = new() { ("Sam", 30), ("Alex", 25) };
int samAge2 = list.First(p => p.Name == "Sam").Age; // O(n) linear scan
Real-world example Storing a cache of user sessions keyed by session ID, where fast lookup by ID is essential.

Common follow-ups: What happens if you try to access a Dictionary key that doesn't exist, using the indexer versus TryGetValue?