C# Interview Question #50

What is the difference between Select() and SelectMany()?

LINQ & Querying Mid-Level Intermediate

Quick Interview Answer

Select projects each input element into one output element or object. SelectMany projects each input element into a sequence and then flattens those nested sequences into one sequence.

Detailed Explanation

Select projects each input element into one output element or object. SelectMany projects each input element into a sequence and then flattens those nested sequences into one sequence.

SelectMany is useful when working with parent-child data, such as customers and their orders or categories and their products.

Code Example

var nested = categories
    .Select(c => c.Products);

var allProducts = categories
    .SelectMany(c => c.Products);