Clean Up Your C# Loops: Flattening Nested Collections with LINQ SelectMany
Source: Dev.to
Introduction
Have you ever dealt with a list within a list and found yourself writing messy nested foreach loops just to get to the data? In C#, the .SelectMany operator provides an elegant way to flatten these nested collections into a single, usable stream.
Traditional Approach
var allItems = new List();
foreach (var order in orders)
{
foreach (var item in order.LineItems)
{
allItems.Add(item);
}
}
This works, but it’s noisy and harder to read at a glance.
Using SelectMany
var allItems = orders.SelectMany(o => o.LineItems).ToList();
SelectMany reaches into each parent object, grabs the child collection, and spreads it out into a single sequence.
Benefits
- Readability – You state what you want to do, not how to loop through it.
- Chainability – You can immediately add
.Where(),.OrderBy(), or other LINQ operators after.SelectManyto further refine your data without adding more loops.
If you’re moving from a loop‑heavy style to a more functional approach in .NET, SelectMany is a tool you’ll reach for constantly!