
SelectMany collapses many elements into a single collection. The resulting collection is of another element type. With this C# method, you must specify how an element can be transformed into a collection of other elements. Then these elements are put into a single enumerable collection.
This C# example program shows the SelectMany extension method. It requires System.Linq.

To start, this program uses an array of string literals. Then, the SelectMany method is used on this array. The argument to SelectMany is a Func lambda expression; it specifies that each string should be converted to a character array. Finally, SelectMany combines all those character arrays and we loop over each char.
String Literal Func Type Lambda Expression Char Array Use ToCharArray Method, Convert String to ArrayProgram that uses SelectMany method [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Input.
string[] array =
{
"dot",
"net",
"perls"
};
// Convert each string in the string array to a character array.
// ... Then combine those character arrays into one.
var result = array.SelectMany(element => element.ToCharArray());
// Display letters.
foreach (char letter in result)
{
Console.WriteLine(letter);
}
}
}
Output
d
o
t
n
e
t
p
e
r
l
s
What are some practical uses of the SelectMany method? Any time you can change an element into an array or collection of parts, you can use SelectMany to simplify your data. If you have an array of strings that are separated by delimiters, you can use SelectMany after splitting them. Then, the final result is an array of all the individual parts of all the strings.
String Array Split String Examples
The SelectMany method provides a way to collapse a collection of elements into a flattened representation of those elements. This means you can simplify the data representations in your program by transforming each element into its parts, and then accessing those parts in a simple IEnumerable collection.
Select Method LINQ Examples