TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# SelectMany Example

This C# example program shows the SelectMany extension method. It requires System.Linq.

SelectMany 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.

Select

Example. 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 LiteralFuncChar ArrayToCharArray

C# program that uses SelectMany method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Input.
	string[] array =
	{
	    "dot",
	    "net",
	    "deves"
	};

	// 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

Discussion. Any time you can change an element into an array or collection of parts, you can use SelectMany to simplify data. 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.

String ArraySplit

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. We then access those parts in an IEnumerable collection.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf