Return the Average Value From a Numeric Sequence

 

The Average operator computes the average of a sequence of numeric values.

System_CAPS_noteNote

The LINQ to SQL translation of Average of integer values is computed as an integer, not as a double.

Example

The following example returns the average of Freight values in the Orders table.

Results from the sample Northwind database would be 78.2442.

System.Nullable<Decimal> averageFreight =
    (from ord in db.Orders
    select ord.Freight)
    .Average();

Console.WriteLine(averageFreight);

Example

The following example returns the average of the unit price of all Products in the Products table.

Results from the sample Northwind database would be 28.8663.

System.Nullable<Decimal> averageUnitPrice =
    (from prod in db.Products
    select prod.UnitPrice)
    .Average();

Console.WriteLine(averageUnitPrice);

Example

The following example uses the Average operator to find those Products whose unit price is higher than the average unit price of the category it belongs to. The example then displays the results in groups.

Note that this example requires the use of the var keyword in C#, because the return type is anonymous.

var priceQuery =
    from prod in db.Products
    group prod by prod.CategoryID into grouping
    select new
    {
        grouping.Key,
        ExpensiveProducts =
            from prod2 in grouping
            where prod2.UnitPrice > grouping.Average(prod3 =>
                prod3.UnitPrice)
        select prod2
    };

foreach (var grp in priceQuery)
{
    Console.WriteLine(grp.Key);
    foreach (var listing in grp.ExpensiveProducts)
    {
        Console.WriteLine(listing.ProductName);
    }
}

If you run this query against the Northwind sample database, the results should resemble of the following:

1

Côte de Blaye

Ipoh Coffee

2

Grandma's Boysenberry Spread

Northwoods Cranberry Sauce

Sirop d'érable

Vegie-spread

3

Sir Rodney's Marmalade

Gumbär Gummibärchen

Schoggi Schokolade

Tarte au sucre

4

Queso Manchego La Pastora

Mascarpone Fabioli

Raclette Courdavault

Camembert Pierrot

Gudbrandsdalsost

Mozzarella di Giovanni

5

Gustaf's Knäckebröd

Gnocchi di nonna Alice

Wimmers gute Semmelknödel

6

Mishi Kobe Niku

Thüringer Rostbratwurst

7

Rössle Sauerkraut

Manjimup Dried Apples

8

Ikura

Carnarvon Tigers

Nord-Ost Matjeshering

Gravad lax

Show: