Lesson 7/31

Tutorials LINQ Mastery

SelectMany: Flattening complex hierarchies

On this page

The Power of Flattening

When you have a 'List of Lists', Select will give you a list containing lists. SelectMany flattens them into a single, unified stream.

1. One-to-Many Relationships

Imagine a Department has many Employees. If you want a list of ALL employees across all departments, SelectMany is your best friend.


// Using Select (returns List<List<Employee>>)
var nested = departments.Select(d => d.Employees);

// Using SelectMany (returns List<Employee>)
var flattened = departments.SelectMany(d => d.Employees);
        

2. Cross Joins (Cross Products)

You can use SelectMany to combine every item in List A with every item in List B. This is the LINQ equivalent of a SQL **CROSS JOIN**.

3. Architect Insight

Q: "When is SelectMany too expensive?"

Architect Answer: "In EF Core, SelectMany is translated into a **JOIN**. While powerful, be careful of 'Cartesian Explosion' where the resulting result set becomes massive. Always combine SelectMany with a Where clause to keep the result set manageable for your server's memory."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details