Saturday, July 5, 2008

Restriction Operators in LINQ

Restriction Operator in LINQ

There is only one restriction operator in LINQ is 'Where'. One of the most used LINQ operators is Where. It restricts the sequence returned by a query based on a predicate provided as an argument.

The following code snippet uses Where to retrieve every element in a sequence that has FirstName equal to Arjun. In this samples we use Object Initilizer concept to create an people object. We can use this Where in two way.

  1. Element based retrival from the source sequence
  2. Position (index) based retrival from the source sequence
First we will see the element based retrival from the source sequence from the people object given below:


List people = new List {
{ ID = 1, LastName = "Kannan", FirstName= "Arjun", Role = 1},
{ ID = 2, LastName = "Heema", FirstName ="Sekar", Role = 2}
};

var query = from p in people
where p.FirstName == "Sekar"
select p;
ObjectDumper.Write(query);


The index based data retrival from the source squenece is given below the same sample given above. Here, index based retrival using Lamda expression for data fetching.

var query = people
.Where((p, index) => p.Role == index && p.Role = 2);
ObjectDumper.Write(query);


The output for above two samples are same as below.

         ID = 2, LastName = "Heema", FirstName ="Sekar", Role = 2

Click here to see more operator available in LINQ.

Happy coding!!!