Where

Simple Where method

The Where method takes one parameter - a predicate. The predicate itself receives one parameter (the object being filtered) and is supposed to return true/false (whether the object should be included in the result or not).

The following example gets all customers from "USA":

List<Customer> customers =
    context.Customers
        .Where(c => c.Country == "USA")
        .ToList();

Logical operators

Logical operators can be used within the Where predicate as follows:

List<Customer> customers =
    context.Customers
        .Where(c => c.Country == "USA" && c.City == "San Francisco")
            .ToList();

Multiple Where methods 

To further limit the result, more Where methods can be specified. The following example produces the same result as the previous one:

List<Customer> customers =
    context.Customers
        .Where(c => c.Country == "USA")
        .Where(c => c.City == "San Francisco")
            .ToList();

Where on child objects

To get the list of of customers with at least 10 orders, use the following:

List<Customer> customers =
    context.Customers
        .Where(c => c.Orders.Count >= 10)
            .ToList();

Other LINQ methods inside the Where method

Where method can also use other LINQ methods within itself. The following example uses Any method and returns only customers that have ever had an order with Freight greater than 100:

List<Customer> customers =
    context.Customers
        .Where(c => c.Orders.Any(o => o.Freight > 100))
            .ToList();

Should you have any questions or found a mistake that needs correcting, feel free to send an email to: info [at] linqtutorial [dot] info


Advertisements :