LINQ Interview Question #21

What is SelectMany in LINQ?

LINQ Fundamentals, Syntax, IEnumerable & IQueryable Junior Beginner

Quick Interview Answer

SelectMany projects each source element to a sequence and then flattens all resulting sequences into one sequence. It is useful for nested collections such as departments containing employees or orders containing order lines.

Detailed Explanation

SelectMany projects each source element to a sequence and then flattens all resulting sequences into one sequence. It is useful for nested collections such as departments containing employees or orders containing order lines.

Select would produce a sequence of sequences, while SelectMany produces a single flattened sequence.

Code Example

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

var productNames = orders
    .SelectMany(o => o.Lines)
    .Select(line => line.ProductName);