Summary: in this tutorial, you will learn how to use the LINQ SelectMany()
method to transform items of a sequence into a single flatted sequence.
Introduction to the LINQ SelectMany() method
The SelectMany()
method takes a sequence of items, performs a transformation on each item, and generates a new sequence of items for each input item. Finally, it combines all the generated immediate sequences into a single flattened sequence.
Here’s the syntax of the SelectMany()
method:
public IEnumerable<TResult> SelectMany<TSource,TResult> (
this IEnumerable<TSource> source,
Func<TSource,IEnumerable<TResult>> selector
);
Code language: C# (cs)
In this syntax:
source
– is the sequence of items with typeIEnumerable<TSource>
to transform.selector
– is a transformation function that applies to each element of the source sequence.
LINQ SelectMany() method
Let’s take some examples of using the SelectMany()
method.
1) Using the LINQ SelectMany() method to flatten a list of arrays of integers
The following example uses the SelectMany()
method to flatten a list of an array of integers and return a IEnumerable<int>
:
using static System.Console;
var numbers = new List<int[]>()
{
new int[] { 1, 2 },
new int[] { 3, 4, 5,},
new int[] { 6, 7, 8}
};
var results = numbers.SelectMany(x => x);
foreach (var number in results)
{
WriteLine(number);
}
Code language: C# (cs)
Objects
1
2
3
4
5
6
7
8
Code language: C# (cs)
2) Using the LINQ SelectMany() method to flatten a list of arrays of strings
Suppose you have an Employee
class with two properties Name
and Skills
. The Skills
property is a list of strings that represent employees’ skills.
public class Employee
{
public string Name { get; set;}
public List<string> Skills { get; set;}
public Employee(string name, List<string> skills)
{
Name = name;
Skills = skills;
}
}
Code language: C# (cs)
The following program uses the SelectMany()
to get all skills of all employees from a list:
using static System.Console;
var employees = new List<Employee>()
{
new Employee
(
name: "John Doe",
skills: new List<string> {"C#","ASP.NET Core","Rest API"}
),
new Employee
(
name: "Jane Doe",
skills: new List<string> {"Python","Django","Fast API"}
),
new Employee
(
name: "Alice Miller",
skills: new List<string> {"JavaScript","Node.js","Express"}
),
};
var skills = employees.SelectMany(e => e.Skills);
foreach (var skill in skills)
{
WriteLine(skill);
}
Code language: C# (cs)
Output:
C#
ASP.NET Core
Rest API
Python
Django
Fast API
JavaScript
Node.js
Express
Code language: C# (cs)
Summary
- Use the LINQ
SelectMany()
method to create a single flattened sequence by transforming items of another sequence.