C# LINQ Aggregation Methods – LYNQ Sum()

The Enumerable.Sum is an extension method from System.Linq namespace. This method returns the sum of numeric values in a collection.


C# LINQ Aggregation Methods – LYNQ Sum()

The Enumerable.Sum is an extension method from System.Linq namespace. This method returns the sum of numeric values in a collection.

1. Sum for Numeric Types

//Gets the sum of values from a list of integer numbers.

var numbers = new List { 1, 2, 4, 8 };
int sum = numbers.Sum();  // sum: 15
//Gets the sum of values from a list of decimal numbers.

var numbers = new List { 8.2m, 2.2m, 6.2m, 3.3m };
decimal sum = numbers.Sum();  // sum: 19.9
//Calling Sum on an empty collection returns 0.

var numbers = new List();  // empty list
int sum = numbers.Sum();        // sum: 0

Sum for Nullable Numeric Types:

using System;  
//Gets sum of values from the list of nullable integers.

var numbers = new List<int?> { 8, 2, null, 3 };
int? sum = numbers.Sum();  // sum: 13

using System;  
//Returns 0 if the collection contains only null values.

var numbers = new List<int?> { null };
int? sum = numbers.Sum();  // sum: 0

using System;  
//Returns 0 if the collection is empty.

var numbers = new List<int?>();  // empty list
int? sum = numbers.Sum();        // sum: 0

Sum with Selector

using System;  
//This example sums the lengths of all strings in the list.

var stringList = new List { "88888888", "22", "666666", "333" };

// these two lines do the same
int lengthSum = stringList.Select(x => x.Length).Sum();  // lengthSum: 19
int lengthSum = stringList.Sum(x => x.Length); 

Sum with Query Syntax

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

var list = new List { 8, 2, 6, 3 };
int sum = (from x in list select x).Sum();  // sum: 19
LINQ query expression to get a sum of numbers that match the specified predicate.

var list = new List { 8, 2, 6, 3 };
int sum = (from x in list where x > 4 select x).Sum();  // sum: 14
LINQ query expression to get a sum of string lengths using a selector.

var list = new List { "88888888", "22", "666666", "333" };
int lengthSum = (from x in list select x.Length).Sum();  // lengthSum: 19

Sum with Group By

This example shows how to calculate a sum for each group. Let’s have players. Each player belongs to a team and has a score. The team total score is the sum of the scores of all players on the team.

using System;  
var players = new List {
    new Player { Name = "Alex", Team = "A", Score = 10 },
    new Player { Name = "Anna", Team = "A", Score = 20 },
    new Player { Name = "Luke", Team = "L", Score = 60 },
    new Player { Name = "Lucy", Team = "L", Score = 40 },
};

var teamTotalScores =
    from player in players
    group player by player.Team into playerGroup
    select new
    {
        Team = playerGroup.Key,
        TotalScore = playerGroup.Sum(x => x.Score),
    };

// teamTotalScores is collection of anonymous objects:
// { Team = "A", TotalScore = 30 }
// { Team = "L", TotalScore = 100 }

Sum Implementation

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

using System;  
public static int Sum(this IEnumerable source)
{
    if (source == null) throw Error.ArgumentNull("source");
    int sum = 0;
    checked {
        foreach (int v in source) sum += v;
    }
    return sum;
}

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

using System;  
public static int? Sum(this IEnumerable<int?> source)
{
    if (source == null) throw Error.ArgumentNull("source");
    int sum = 0;
    checked {
        foreach (int? v in source) {
            if (v != null) sum += v.GetValueOrDefault();
        }
    }
    return sum;
}


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Share this:
We will be happy to hear your thoughts

      Leave a reply

      www.troubleshootyourself.com
      Logo