LINQ Interview Question #87

What is the difference between ToDictionary and ToLookup?

Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate

Quick Interview Answer

ToDictionary expects one value per unique key and throws when duplicate keys are produced. ToLookup supports multiple elements for the same key.

Detailed Explanation

ToDictionary expects one value per unique key and throws when duplicate keys are produced. ToLookup supports multiple elements for the same key.

ToLookup therefore represents a one-to-many mapping, while Dictionary is normally used for a one-to-one key mapping.

Code Example

var byId = products.ToDictionary(p => p.Id);

var byCategory = products
    .ToLookup(p => p.CategoryId);