SelectMany
This C# method, from LINQ, collapses many elements into a single collection. The resulting collection is of another element type.
We specify how an element is transformed into a collection of other elements. For example, we can change string
elements into char
array elements.
To start, this program uses an array of string
literals. Then, the SelectMany
method is used on this array. Each string
is transformed in SelectMany
.
SelectMany
is a Func
lambda expression. It specifies that each string
should be converted to a character array.SelectMany
combines all those character arrays and we loop over each char
.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
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.
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.