Compute the Sum of Values in a Numeric Sequence

Use the Sum operator to compute the sum of numeric values in a sequence.

Note the following characteristics of the Sum operator in LINQ to SQL:

  • The Standard Query Operator aggregate operator Sum evaluates to zero for an empty sequence or a sequence that contains only nulls. In LINQ to SQL, the semantics of SQL are left unchanged. For this reason, Sum evaluates to null instead of to zero for an empty sequence or for a sequence that contains only nulls.

  • SQL limitations on intermediate results apply to aggregates in LINQ to SQL. Sum of 32-bit integer quantities is not computed by using 64-bit results, and overflow can occur for the LINQ to SQL translation of Sum. This possibility exists even if the Standard Query Operator implementation does not cause an overflow for the corresponding in-memory sequence.

Example 1

The following example finds the total freight of all orders in the Order table.

If you run this query against the Northwind sample database, the output is: 64942.6900.

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

Console.WriteLine(totalFreight);
Dim totalFreight = Aggregate ord In db.Orders _
                   Into Sum(ord.Freight)

Console.WriteLine(totalFreight)

Example 2

The following example finds the total number of units on order for all products.

If you run this query against the Northwind sample database, the output is: 780.

Note that you must cast short types (for example, UnitsOnOrder) because Sum has no overload for short types.

System.Nullable<long> totalUnitsOnOrder =
    (from prod in db.Products
    select (long)prod.UnitsOnOrder)
    .Sum();

Console.WriteLine(totalUnitsOnOrder);
Dim totalUnitsOnOrder = Aggregate prod In db.Products _
                        Into Sum(prod.UnitsOnOrder)

Console.WriteLine(totalUnitsOnOrder)

See also