0
0
C Sharp (C#)programming~5 mins

SelectMany for flattening in C Sharp (C#)

Choose your learning style9 modes available
Introduction

SelectMany helps you take many small lists inside a big list and turn them into one big list. It makes it easy to work with all items together.

You have a list of classrooms, each with a list of students, and want one list of all students.
You have a list of orders, each with a list of products, and want one list of all products ordered.
You have a list of books, each with a list of authors, and want one list of all authors.
You want to combine multiple lists inside a list into a single list to process easily.
Syntax
C Sharp (C#)
var flatList = bigList.SelectMany(innerList => innerList);

SelectMany takes a function that returns a collection for each item.

It then merges all those collections into one single collection.

Examples
This flattens a list of lists of numbers into one list: 1, 2, 3, 4.
C Sharp (C#)
var numbers = new List<List<int>> {
    new List<int> {1, 2},
    new List<int> {3, 4}
};
var flat = numbers.SelectMany(x => x);
This flattens arrays of words into one list of words.
C Sharp (C#)
var words = new List<string[]> {
    new string[] {"apple", "banana"},
    new string[] {"cherry"}
};
var allWords = words.SelectMany(arr => arr);
This gets all pets from all people into one list.
C Sharp (C#)
var people = new List<Person> {
    new Person { Name = "Alice", Pets = new List<string>{"Dog", "Cat"} },
    new Person { Name = "Bob", Pets = new List<string>{"Fish"} }
};
var allPets = people.SelectMany(p => p.Pets);
Sample Program

This program creates classrooms with students and uses SelectMany to get one list of all students. Then it prints each student.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    class Classroom
    {
        public string Name { get; set; }
        public List<string> Students { get; set; }
    }

    static void Main()
    {
        var classrooms = new List<Classroom>
        {
            new Classroom { Name = "Class A", Students = new List<string>{"John", "Jane"} },
            new Classroom { Name = "Class B", Students = new List<string>{"Tom", "Lucy"} }
        };

        var allStudents = classrooms.SelectMany(c => c.Students);

        foreach (var student in allStudents)
        {
            Console.WriteLine(student);
        }
    }
}
OutputSuccess
Important Notes

SelectMany is great for flattening nested collections into one.

If you use Select instead, you get a list of lists, not a flat list.

Remember to include using System.Linq; to use SelectMany.

Summary

SelectMany turns many small lists inside a big list into one big list.

It helps when you want to work with all items together instead of nested groups.

Use it with a function that picks the inner list from each item.