Have you ever dealt with a "List within a List" and found yourself writing messy nested foreach loops just to get to the data?
As a developer who loves puzzles (and LEGO Technic!), I’m always looking for ways to simplify complex structures. In C#, the .SelectMany operator is one of the most elegant ways to "flatten" these nested collections into a single, usable stream.
The Problem
Imagine you have a list of Orders, and each order contains a list of LineItems. If you want a single list of every item sold across all orders, the traditional way looks like this:
var allItems = new List<LineItem>();
foreach (var order in orders)
{
foreach (var item in order.LineItems)
{
allItems.Add(item);
}
}
This works, but it's "noisy." It’s hard to read at a glance.
The Solution: SelectMany
With LINQ, we can achieve the same result in a single line of code. Think of SelectMany as a way to reach into each parent object, grab the child collection, and spread it out on the table.
var allItems = orders.SelectMany(o => o.LineItems).ToList();
Why this is better
- Readability: You state what you want to do, not how to loop through it.
-
Chainability: You can immediately add a
.Where()or.OrderBy()after the.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!
Top comments (0)