Aggregates

Count

To get the number of customers, you can use the Count like this:

int customerCount =
    context.Customers
        .Count();

Count can also take a predicate as a parameter. To get the number of customers from USA, use this:

int customerCount =
    context.Customers
        .Count(c => c.Country == "USA");

Any

Any returns True/False depending on whether the result contains at least 1 result. Just like count, it can be parameter-less or it can take a predicate. The following example uses the predicate option:

bool customersFromUsa =
    context.Customers
        .Any(c => c.Country == "USA");

Sum

Sum calculates a total of the selector you pass to it as a parameter:

decimal? freightSum =
    context.Orders
        .Sum(o => o.Freight);

Average

Average calculates an average of the selector you pass to it as a parameter:

decimal? freightAverage =
    context.Orders
        .Average(o => o.Freight);

Min

Min finds the lowest value of the selector you pass to it as a parameter:

decimal? freightMin =
    context.Orders
        .Min(o => o.Freight);

Max

Max finds the highest value of the selector you pass to it as a parameter:

decimal? freightMax =
    context.Orders
        .Max(o => o.Freight);

Watch out for no results

If the LINQ query returns no results, the aggregate methods will fail. DefaultIfEmpty method needs to be used in these cases. If in the following example no order details would exist, a default (empty) collection of order details will be passed along after the DefaultIfEmpty() method. Using this empty collection, Max method will be able to calculate the maximum discount - 0:

float maxDiscount =
    context.Order_Details
        .DefaultIfEmpty()
        .Max(o => o.Discount);

The DefaultIfEmpty method can also be used when selecting a single type. If that type is a Nullable, the default value for DefaultIfEmpty will mean NULL. This NULL needs to be handled properly later on - here we use the coalesce operator:

decimal? freightSum =
    context.Orders
        .Select(o => o.Freight)
        .DefaultIfEmpty()
        .Sum(o => o ?? 0);

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 :