.NETMedium
What is the difference between Dictionary and ILookup in LINQ?
Dictionary<K, V> — one key → one value. Throws on duplicate keys.
var byId = products.ToDictionary(p => p.Id); // crashes if two products share an Id
ILookup<K, V> — one key → many values. Tolerates duplicates by design; missing keys return an empty IEnumerable<V>.
var byCategory = products.ToLookup(p => p.CategoryId);
foreach (var p in byCategory[someCategoryId]) { /* iterate */ }
foreach (var p in byCategory[missingId]) { /* empty — no exception */ }
Why ILookup is underrated:
- Built once, queried many times (vs GroupBy which is lazy)
- Missing key returns empty rather than throwing
- O(1) lookup, like a Dictionary
Choose Dictionary when you have a true 1:1 key mapping.
Choose ILookup when the key is one-to-many (orders by customer, employees by department) AND you'll do multiple lookups against the same data.
Choose GroupBy when you only iterate once.
// One-time iteration: GroupBy is fine
foreach (var g in orders.GroupBy(o => o.CustomerId)) { /* ... */ }
// Multiple lookups: ToLookup is faster
var lookup = orders.ToLookup(o => o.CustomerId);
foreach (var id in topCustomerIds) ProcessOrders(lookup[id]);