Saturday, July 5, 2008

Projection Operators in LINQ

Projection Operators in LINQ

There are two Projection Operators in LINQ namly 'Select' and 'SelectMany'.

1. Select :

Just like SELECT in SQL, the Select operator specifies which elements are to be retrieved. The record or data retrival based on two models. One is element based selection and another one is Index based selection.

public void KannanLINQDemo() {
int[] digits = { 1, 5, 6, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };


var textNums = from n in digits
select strings[n];

Console.WriteLine("Digit strings:");
foreach (var s in textNums) {
Console.WriteLine(s);
}
}

The output is
           one
five
six
two
zero

Let we see one more sample with different select usage. To select the people whose Role is 2 and their last name starts with the letter 'H' from the following people lists.

List people = new List {               
{ ID = 1, LastName = "Kannan", FirstName= "Arjun", RoleId = 1},
{ ID = 2, LastName = "Heema", FirstName ="Sekar", RoleId = 2}
{ ID = 3, LastName = "Seema", FirstName ="Sekar", RoleId = 2}
{ ID = 4, LastName = "Jillary", FirstName ="Sekar", RoleId = 3}
};
var query = from p in people
where p.RoleId == 2 && p.LastName.StartWith("H")
select p;
ObjectDumper.Write(query);


The output is
    ID = 2, LastName = Heema, FirstName =Sekar, RoleId = 2

2. SelectMany

Transforms each input element, then flattens and concatenates the resultant subsequences . SelectMany concatenates subsequences into a single flat output sequence. SelectMany can be used to expand child sequences, flatten nested collections, and join two collections into a flat output sequence. The SQL equivalents of SelectMany is INNER JOIN, LEFT OUTER JOIN, CROSS JOIN .

For an example, take the above people object and let we take the following roles objects.

List roles = new List {
{ ID = 1, RoleDescription = "Manager" },
{ ID = 2, RoleDescription = "Team Leader" }
{ ID = 3, RoleDescription = "Developer" }

};
To select the first people's Firstname, LastName and their role description from the above objects. The solution is
var query = people
.Where(p => p.ID == 1)
.SelectMany(p => roles
.Where(r => r.ID == p.ID)
.Select(r => new { p.FirstName,
p.LastName,
r.RoleDescription}
)
);
The output is
LastName = Kannan FirstName= Arjun RoleDescription = Manager

Click here to see more operator available in LINQ.

Happy coding!!!