Summing the elements of a sequence with LINQ C#
July 23, 2014 Leave a comment
Say you have the following numeric sequence:
IEnumerable<int> integers = Enumerable.Range(1, 100);
If you don’t know what the Range operator does, then start here.
You can find the sum of the elements in the sequence using the Sum LINQ operator:
int sum = integers.Sum();
…which gives 5050. The Sum operator obviously only works with numeric elements such as int, long, decimal and double. You can sum specific elements of an object using the overloaded Sum operator.
Take the following objects:
public class Concert { public int SingerId { get; set; } public int ConcertCount { get; set; } public int Year { get; set; } } IEnumerable<Concert> concerts = new List<Concert>() { new Concert(){SingerId = 1, ConcertCount = 53, Year = 1979} , new Concert(){SingerId = 1, ConcertCount = 74, Year = 1980} , new Concert(){SingerId = 1, ConcertCount = 38, Year = 1981} , new Concert(){SingerId = 2, ConcertCount = 43, Year = 1970} , new Concert(){SingerId = 2, ConcertCount = 64, Year = 1968} , new Concert(){SingerId = 3, ConcertCount = 32, Year = 1960} , new Concert(){SingerId = 3, ConcertCount = 51, Year = 1961} , new Concert(){SingerId = 3, ConcertCount = 95, Year = 1962} , new Concert(){SingerId = 4, ConcertCount = 42, Year = 1950} , new Concert(){SingerId = 4, ConcertCount = 12, Year = 1951} , new Concert(){SingerId = 5, ConcertCount = 53, Year = 1983} };
You can get the total number of concerts in the collection by specifying the property selector in a lambda expression as follows:
int allConcerts = concerts.Sum(c => c.ConcertCount);
…which yields 557.
View the list of posts on LINQ here.