0
0
CsharpHow-ToBeginner · 4 min read

How to Use LINQ SelectMany in C# - Simple Guide

Use SelectMany in C# LINQ to flatten nested collections into one sequence by projecting each element to an IEnumerable and concatenating the results. It is useful when you have collections inside collections and want to work with all inner elements as a single list.
📐

Syntax

The SelectMany method projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

Basic syntax:

var result = source.SelectMany(item => item.CollectionProperty);

Explanation:

  • source: The original collection of items.
  • item => item.CollectionProperty: A function that selects a collection from each item.
  • SelectMany: Flattens all these collections into one sequence.
csharp
var result = source.SelectMany(item => item.CollectionProperty);
💻

Example

This example shows how to use SelectMany to flatten a list of students, each with a list of their favorite subjects, into one list of all subjects.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Student
{
    public string Name { get; set; }
    public List<string> FavoriteSubjects { get; set; }
}

class Program
{
    static void Main()
    {
        var students = new List<Student>
        {
            new Student { Name = "Alice", FavoriteSubjects = new List<string> { "Math", "Physics" } },
            new Student { Name = "Bob", FavoriteSubjects = new List<string> { "Biology", "Chemistry" } },
            new Student { Name = "Charlie", FavoriteSubjects = new List<string> { "History" } }
        };

        var allSubjects = students.SelectMany(s => s.FavoriteSubjects);

        foreach (var subject in allSubjects)
        {
            Console.WriteLine(subject);
        }
    }
}
Output
Math Physics Biology Chemistry History
⚠️

Common Pitfalls

Common mistakes when using SelectMany include:

  • Using Select instead of SelectMany, which results in a collection of collections instead of a flattened list.
  • Not returning an IEnumerable from the selector function, causing compile errors.
  • Confusing SelectMany with Where or Select when filtering or projecting.

Example of wrong vs right usage:

csharp
var nestedLists = new List<List<int>>
{
    new List<int> {1, 2},
    new List<int> {3, 4}
};

// Wrong: returns List<List<int>>
var wrong = nestedLists.Select(list => list);

// Right: flattens to List<int>
var right = nestedLists.SelectMany(list => list);
📊

Quick Reference

Tips for using SelectMany:

  • Use it to flatten nested collections into a single sequence.
  • The selector function must return an IEnumerable.
  • It is useful for querying complex data structures like lists of lists.
  • Combine with other LINQ methods like Where or OrderBy for powerful queries.

Key Takeaways

SelectMany flattens nested collections into one sequence by projecting each element to an IEnumerable.
Always return an IEnumerable from the selector function passed to SelectMany.
Use SelectMany instead of Select when you want a single flat list, not a list of lists.
SelectMany works well with other LINQ methods for complex data queries.
Common mistake: using Select returns nested collections, not flattened results.