Select and SelectMany

We use Select in LINQ when we need to select some values from a collection. For example, in the following code syntax, we have declared an array of integers and are selecting all of the numbers present in the array:

int[] numbers = new int[3] { 0, 1, 2 };
var numQuery =
from num in numbers
select num;

foreach(var n in numQuery)
{
Console.Write(n);
}

Therefore, if the preceding code is executed, it will print all of the numbers present in the array. The following is the output of the preceding code snippet:

We use Select when we need to select a value from a collection. However, in scenarios where we need to select values from nested collections, that is, a collection of collections, we use the SelectMany operator. Refer to the following code example, in which we are using the SelectMany operator to retrieve individual characters from string objects present in a string array:

string[] array =
{
"Introduction",
"In",
"C#"
};
var result = array.SelectMany(element => element.ToCharArray());
foreach (char letter in result)
{
Console.Write(letter);
}

 The following would be the output of the program:

In the preceding program, the source of data is an array of strings. Now, strings are again an array of characters. Using SelectMany, we have directly looped through the characters present in the Introduction, In, and C# strings. Hence, using SelectMany, we can perform actions using fewer statements than it would take otherwise. 

In the next section, we will look at the Join operator, which helps us join two collections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.74.3