Back
Close

Using C# LINQ - A Practical Overview

player_one
69.3K views

SelectMany(<selector>) method

The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence. For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example:

int[][] arrays = {
    new[] {1, 2, 3},
    new[] {4},
    new[] {5, 6, 7, 8},
    new[] {12, 14}
};
// Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 }
IEnumerable<int> result = arrays.SelectMany(array => array);

Notice that in the code above, we passed an identity lambda expression into the SelectMany() call. This causes the elements of the constituent arrays to be copied into the resultant sequence without alteration.

You can also perform transformations on the constituent sequences, as shown in this example utilizing a list of lists:

List<List<int>> lists = new List<List<int>> {
    new List<int> {1, 2, 3},
    new List<int> {12},
    new List<int> {5, 6, 5, 7},
    new List<int> {10, 10, 10, 12}
};
// Will return { 1, 2, 3, 12, 5, 6, 7, 10, 12 }
IEnumerable<int> result = lists.SelectMany(list => list.Distinct());
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants