LINQ Interview Question #62

What is the difference between GroupBy and ToLookup?

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

Quick Interview Answer

GroupBy commonly returns a deferred sequence of groups. ToLookup immediately enumerates the source and creates a lookup structure that maps keys to one or more values.

Detailed Explanation

GroupBy commonly returns a deferred sequence of groups. ToLookup immediately enumerates the source and creates a lookup structure that maps keys to one or more values.

A lookup is useful when repeated key-based access is required after materialization. GroupBy is often preferable when the goal is simply to compose a grouping query.

Code Example

var grouped = employees
    .GroupBy(e => e.DepartmentId);

var lookup = employees
    .ToLookup(e => e.DepartmentId);

var salesEmployees = lookup[5];