LINQ Interview Question #140

How can LINQ flatten a hierarchy while keeping parent information?

Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Use SelectMany with a result selector, or project child elements together with values from the parent. This converts nested collections into a flat sequence while preserving context.

Detailed Explanation

Use SelectMany with a result selector, or project child elements together with values from the parent. This converts nested collections into a flat sequence while preserving context.

It is useful for orders and lines, departments and employees, categories and products, and similar one-to-many structures.

Code Example

var lines = orders.SelectMany(
    order => order.Lines,
    (order, line) => new
    {
        OrderId = order.Id,
        order.CustomerId,
        line.ProductId,
        line.Quantity
    });