The Where
operator is a LINQ query operator that filters a sequence of elements based on a Boolean predicate. The predicate is a function that takes an element of the sequence as an input and returns a Boolean value indicating whether the element should be included in the filtered sequence or not.
Here is an example of how you might use the Where
operator to filter a list of integers:
1 2 3 4 5 6 7 8 9 10 11 | List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Use the Where operator to filter the list of numbers IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0); foreach (int number in evenNumbers) { Console.WriteLine(number); } |
In this example, the Where
operator is used to filter the numbers
list and return only the even numbers. The predicate passed to the Where
operator is a lambda expression that takes an integer n
as an input and returns true
if n
is even (i.e. if n % 2 == 0
) and false
otherwise.
The query is executed when the foreach
loop is used to enumerate the results, and it will print all the even numbers returned by the query.
You can also chain multiple Where
operators to create more complex queries, for example:
1 2 3 | IEnumerable<Person> adults = people.Where(p => p.Age >= 18).Where(p => p.IsEmployed); |
This query will return only the people who are 18 or older and employed.
It’s worth noting that the Where
operator returns an IEnumerable<T>
object, which is a lazy-evaluated sequence, so the query is not executed until the results are enumerated or materialized.
Also, you can use Where
operator to filter on multiple criteria, for example:
1 2 3 | IEnumerable<Person> adults = people.Where(p => p.Age >= 18 && p.Gender == Gender.Female); |
This query will return only the people who are 18 or older and Female.
It is also possible to use the Where
operator with other query operators like Select
, OrderBy
, and GroupBy
to create more complex queries and manipulate the data further. For example:
1 2 3 4 5 6 | var adultMales = from p in people where p.Age >= 18 && p.Gender == Gender.Male orderby p.LastName select new {p.Name, p.Age}; |
This query will filter out only adult males, then sort them by LastName and select only name and age of the people
It’s also possible to use the Where
operator with query syntax or method syntax interchangebly, depending on the developer’s preference and readability of the code.
Here’s another example of how you might use the Where
operator to filter and group a list of Order
objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | List<Order> orders = GetOrders(); // Use the Where and GroupBy operators to filter and group the orders var ordersByCustomer = orders.Where(o => o.TotalAmount > 1000) .GroupBy(o => o.Customer.Country) .Select(g => new { Country = g.Key, Orders = g.ToList() }); foreach (var group in ordersByCustomer) { Console.WriteLine("Country: " + group.Country); foreach (var order in group.Orders) { Console.WriteLine(" Order: " + order.Id + " - " + order.TotalAmount); } } |
In this example, GetOrders
method returns a list of Order
objects. Then, using the Where
operator, a query is written to select all Order
objects from the list whose total amount is greater than 1000.
Then, using the GroupBy
operator, the orders are grouped by the country of the customer. The Select
operator is used to create a new anonymous type, which includes the country name as the key and the list of orders as the value.
The query is executed when the foreach
loop is used to enumerate the results, and it will print the country name and the details of each order returned by the query, grouped by the country of the customer.
The Where
operator is used first to filter the orders with total amount greater than 1000. Then GroupBy
operator creates a new sequence of groups where each group has a key (in this case the country of the customer) and a sequence of elements that have that key. Finally, the Select
operator is used to create a new anonymous type, which includes the country name as the key and the list of orders as the value, from each group.
This example shows how you can use the Where
operator to filter a sequence of elements, and then use the GroupBy
operator to group the filtered elements based on a specific key, and then use the Select
operator to create a new sequence of elements from the groups.
Here’s another example of how you might use the Where
operator to filter and join two lists:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | List<Employee> employees = GetEmployees(); List<Department> departments = GetDepartments(); // Use the Where and Join operators to filter and join the employees and departments var employeesInITDepartment = from e in employees join d in departments on e.DepartmentId equals d.Id where d.Name == "IT" select new {e.Name, e.Salary, d.Name}; foreach (var emp in employeesInITDepartment) { Console.WriteLine("Name: " + emp.Name + " | Salary: " + emp.Salary + " | Department: " + emp.Name); } |
In this example, GetEmployees
and GetDepartments
methods return a list of Employee
and Department
objects respectively. Then, using the Where
operator, a query is written to join the two lists and select all Employee
objects from the list whose department name is “IT”.
The Join
operator is used to join the two lists on the DepartmentId
of the Employee
object and the Id
of the Department
object. The Where
operator is used to filter the joined data, to only include employees whose department name is “IT”.
The query is executed when the foreach
loop is used to enumerate the results, and it will print the name, salary and department of each employee returned by the query, who works in the IT department.
This example shows how you can use the Where
operator to filter the results of a join query between two lists and select only the elements that meet a certain condition.
[…] Where: Filters a sequence based on a Boolean predicate […]