One result

To get a single result instead of a collection, use Single, SingleOrDefault, First or FirstOrDefault methods. All of these methods can take 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 predicate parameter itself is optional as the selection can be limited by a preceding Where method, for example.

Single

Single method, just as all of the following, returns a single results. The method will, however, throw an exception if there is no or more than one result available. The following example has the predicate set in such a way, that exactly one record will match it:

Customer customer =
    context.Customers
        .Single(c => c.CustomerID == "SUPRD");

SingleOrDefault

SingleOrDefault behaves exactly as Single, except it returns a default value (NULL in our example) when zero results match the predicate:

Customer customer =
    context.Customers
        .SingleOrDefault(c => c.CustomerID == "NOSUCHID");

First

First method returns the first match if more than one match is available. It will throw an exception if there is no match:

Customer customer =
    context.Customers
        .First(c => c.Country == "USA");

FirstOrDefault

FirstOrDefault method returns the first match if more than one match is available. It will return a default value (NULL in our example) when zero results match the predicate:

Customer customer =
    context.Customers
        .FirstOrDefault(c => c.Country == "NOSUCHCOUNTRY");

Predicate through Where

As mentioned earlier, the predicate parameter in all the example above, is optional. First and FirstOrDefault methods can be used directly. For Single and SingleOrDefault, as the need no more than one result, a Where method can be used:

Customer customer =
    context.Customers
        .Where(c => c.CustomerID == "SUPRD")
        .Single();

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 :