There are two types of Projection operators in LINQ: Select and SelectMany.
Select Operator
The projection operators take an input sequence, performs some projection on the sequence and returns the sequence. The number of items in the input sequence remain same after projection, unless or until some lambda expression is used which filters records. Have a look at the following example to see how Select operator works.
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpTutorials {
class Tutorial {
static void Main() {
// An array sequence with some items
int[] randomnums = { 1, 12, 45, 32, 65, 23, 57, 23, 45, 12, 34, 90, 27, 48, 10 };
// Select query to double the num values.
IEnumerable<int> doublenums = randomnums.Select(n => n * 2);
foreach (int val in doublenums) Console.Write(val+" ");
Console.WriteLine("");
//Performing indexed Projection
IEnumerable<int> indexednums = randomnums.Select((j,k) => j *k);
foreach (int val in indexednums) Console.WriteLine(val);
Console.WriteLine("");
Console.ReadKey();
}
}
}
In above code, a collection of some random numbers have been created. Next Select operator is applied on this operator and returns a collection where each item is twice of its original value. This means that the numbers of items remain some, however they have been doubled. Also, In above example, Indexed projection is used where each item is multiplied with its own index number and the resultant sequence is returned.
SelectMany Operator
SelectMany query is used to join multiple sub-sequences into one and returns the resultant sequence as a flat single sequence.
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpTutorials {
class Tutorial {
static void Main() {
string[] cararray = { "Ford", "BMW", "Honda", "Toyota", "Suzuki" };
// Here each car name will be converted to character array
// Then all these character arrays will be merged into a collection
// of characters via SelectManny
IEnumerable<char> charsinallchar = cararray.SelectMany(c => c.ToCharArray());
foreach ( char c in charsinallchar) Console.Write(c+"|");
Console.ReadKey();
}
}
}
In the above code, a string type array carrarray has been defined which contain names of some cars. Here the SelectMany query converts all these items in the cararray into individual character arrays via To.CharArray() and then all of these sequences are merged into one sequence of characters.