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.
- Element based retrival from the source sequence
- Position (index) based retrival from the source sequence
Listpeople = 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!!!