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.
var numbers = new List<int> { 8, 2, 6, 3 };
int sum = numbers.Sum(); // sum: 19
Gets sum of values from list of decimal numbers.
var numbers = new List<decimal> { 8.1m, 2.2m, 6.1m, 3.3m };
decimal sum = numbers.Sum(); // sum: 19.7
Calling Sum on empty collection returns 0.
var numbers = new List<int>(); // empty list
int sum = numbers.Sum(); // sum: 0
Sum for Nullable Numeric Types
Gets sum of values from list of nullable integers.
var numbers = new List<int?> { 8, 2, null, 3 };
int? sum = numbers.Sum(); // sum: 13
Returns 0 if the collection contains only null values.
var numbers = new List<int?> { null };
int? sum = numbers.Sum(); // sum: 0
Returns 0 if the collection is empty.
var numbers = new List<int?>(); // empty list
int? sum = numbers.Sum(); // sum: 0
Sum with Selector
This example sums lengths of all strings in the list.
var stringList = new List<string> { "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); // lengthSum: 19
Sum with Query Syntax
LINQ query expression to get sum of numeric values in the collection.
var list = new List<int> { 8, 2, 6, 3 };
int sum = (from x in list select x).Sum(); // sum: 19
LINQ query expression to get sum of numbers which match specified predicate.
var list = new List<int> { 8, 2, 6, 3 };
int sum = (from x in list where x > 4 select x).Sum(); // sum: 14
LINQ query expression to get sum of string lengths using selector.
var list = new List<string> { "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 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.
var players = new List<Player> {
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),
};
No comments:
Post a Comment