Flatten Nested Collections with SelectMany
in C#
When dealing with nested collections in C#, the SelectMany
method is a powerful tool for efficiently flattening these collections. Suppose you have a list of departments, where each department contains a list of employees. Using SelectMany
in C# allows you to easily combine all employees into a single, flat list. This method simplifies the task of handling nested data and significantly enhances code readability.
Problem Overview
Imagine you have a list of departments where each department contains a list of employees:
public class Employee
{
public string Name { get; set; }
}
public class Department
{
public List Employees { get; set; }
}
List departments = new List
{
new Department
{
Employees = new List
{
new Employee { Name = "Alice" },
new Employee { Name = "Bob" }
}
},
new Department
{
Employees = new List
{
new Employee { Name = "Charlie" },
new Employee { Name = "David" }
}
}
};
Here, departments
is a list where each item is a Department
object with a list of Employee
objects. The challenge is to extract a single list of all employees from these nested collections.
Traditional Approach: Nested Loops
Without SelectMany
, you might use nested loops to flatten this structure:
List<Employee> allEmployees = new List<Employee>();
foreach (var department in departments)
{
foreach (var employee in department.Employees)
{
allEmployees.Add(employee);
}
}
This approach works but can become cumbersome and harder to read, especially as the complexity of your data structures increases.
Using SelectMany
in C#
The SelectMany
method provides a more elegant and readable way to achieve the same result. It flattens the nested collections into a single collection with a single line of code:
List<Employee> allEmployees = departments
.SelectMany(department => department.Employees)
.ToList();
Another example
Read also about SelectMany in C#
Learn .NET