LINQ Interview Question #63

What is a Lookup<TKey,TElement>?

Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate

Quick Interview Answer

A Lookup<TKey,TElement> is a one-to-many key-based collection produced by ToLookup. Unlike Dictionary<TKey,TValue>, each key can map to multiple elements.

Detailed Explanation

A Lookup<TKey,TElement> is a one-to-many key-based collection produced by ToLookup. Unlike Dictionary<TKey,TValue>, each key can map to multiple elements.

Requesting a missing key returns an empty sequence rather than throwing a KeyNotFoundException.

Code Example

ILookup<int, Employee> byDepartment =
    employees.ToLookup(e => e.DepartmentId);

foreach (var employee in byDepartment[10])
{
    Console.WriteLine(employee.Name);
}