Monday, July 15, 2013

LINQ 11- Filtering with Where Clause

One of the important operation in list of values is filtering. in LINQ filtering can be done with where clause or Where extension method.

 

Where clause receives value of each element and needs an expression that returns a boolean value based on the input element. Result will be the list of elements which results true while evaluating the where clause.

 

Sample 1

Extension Method

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Where(number => number > 2);

LINQ

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected =

    from number in numbers where number > 2 select number;

Sample 2

Extension Method

IEnumerable<Employee> managers = employees.Where(employee => employee.Role==”Manager”);

LINQ

IEnumerable<Employee> managers =

    from employee in employees

    where employee.Role==”Manager”

    select employee;

No comments:

Post a Comment