LINQ Interview Question #33
How can SelectMany preserve information from the parent object?
Filtering, Projection, Ordering & Element Operators Junior Beginner
Quick Interview Answer
SelectMany has overloads that support a result selector, or the projection can create an object containing values from both the parent and child.
Detailed Explanation
SelectMany has overloads that support a result selector, or the projection can create an object containing values from both the parent and child.
This is useful when flattening nested data while retaining contextual information such as the order ID alongside each order line.
Code Example
var result = orders.SelectMany(
order => order.Lines,
(order, line) => new
{
OrderId = order.Id,
line.ProductName,
line.Quantity
});