Clean Up Your C# Loops: Flattening Nested Collections with LINQ SelectMany

Published: (December 31, 2025 at 01:42 PM EST)
1 min read
Source: Dev.to

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 .SelectMany to 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!

Back to Blog

Related posts

Read more »

C# Smart Enums: advanced

!Cover image for C Smart Enums: advancedhttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-upload...

C# Smart Enums: optimized

The Problem: The “LINQ Tax” In Part 1 we replaced magic numbers with records. To find a specific status we used LINQ: csharp var status = Status.All.SingleOrDe...

Starting My Journey into C# .NET

Introduction I haven’t mastered Python yet, but I’ve decided to begin studying C and .NET as my next step. While attending university, I explored several progr...