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
- MSDN Enumerable.Sum - .NET Framework documentation
- LINQ Aggregation Methods
- LINQ Sum - gets sum of numeric collection
- LINQ Max - gets maximal item from collection
- LINQ Min - gets minimal item from collection
- LINQ Count - counts number of items in a collection (result type is Int32)
- LINQ LongCount - counts number of items in a collection (result type is Int64)
- LINQ Average - computes average value of numeric collection
- LINQ Aggregate - applies aggregate function to a collection
- C# List - illustrative examples of all List<T> methods
- C# foreach - how foreach and IEnumerable works debuggable online