SelectMany. This C# method, from LINQ, collapses many elements into a single collection. The resulting collection is of another element type.
C# method notes. We specify how an element is transformed into a collection of other elements. For example, we can change string elements into char array elements.
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);
}
}
}d
o
t
n
e
t
p
e
r
l
s
Discussion. If you can change an element into separate parts, you can use SelectMany. If you have an array of strings 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.
A summary. This method collapses a collection of elements. It yields a flattened representation of elements. We simplify data representations by transforming each element into its parts.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 20, 2022 (edit).