C# Linq

Linq Sum Method in C# with Examples

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();).

The following example calculates the sum of all integers present in the collection.

Calculate the sum of all numbers which is greater than 50.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.