LINQ Interview Question #32

What is the difference between Select and SelectMany?

Filtering, Projection, Ordering & Element Operators Junior Beginner

Quick Interview Answer

Select maps each source element to one result. If that result is itself a collection, Select produces a sequence of collections. SelectMany maps each source element to a sequence and then flattens all those sequences into one sequence.

Detailed Explanation

Select maps each source element to one result. If that result is itself a collection, Select produces a sequence of collections. SelectMany maps each source element to a sequence and then flattens all those sequences into one sequence.

SelectMany is commonly used with nested collections such as departments and employees, orders and order lines, or categories and products.

Code Example

var nested = orders
    .Select(o => o.Lines);

var flattened = orders
    .SelectMany(o => o.Lines);