Sum (LINQ)

Enumerable.Sum is extension method from System.Linq namespace. It returns sum of numeric values in collection.

Sum for Numeric Types

Gets sum of values from list of integer numbers.

Gets sum of values from list of decimal numbers.

Calling Sum on empty collection returns 0.

Sum for Nullable Numeric Types

Gets sum of values from list of nullable integers.

Returns 0 if the collection contains only null values.

Returns 0 if the collection is empty.

Sum with Selector

This example sums lengths of all strings in the list.

Sum with Query Syntax

LINQ query expression to get sum of numeric values in the collection.

LINQ query expression to get sum of numbers which match specified predicate.

LINQ query expression to get sum of string lengths using selector.

Sum with Group By

This example shows how to calculate sum for each group. Lets have players. Each player belongs to a team and have a score. Team total score is sum of score of all players in the team.

Sum Implementation

This is .NET Framework implementation of Enumerable.Sum method for collection of numeric type (in this case IEnumerable<int>).

This is .NET Framework implementation of Enumerable.Sum method for collection of nullable numeric type (in this case IEnumerable<int?>). Note that it ignores null values (see line if (v != null) sum += v.GetValueOrDefault();).


See also

By Jan Slama, 16-Apr-2016
;