Sum is a LINQ functionality which calculates total number of numeric items of a collection. In this article you can find examples of usage with list of primitive types (in our case integers) and also list of complex types.
List of integers
1 |
var items = new List<int>() { 1, 2, 3, 4, 5 }; |
Total number can be calculated by calling Sum function without any arguments. It just adds up all figures.
1 |
var total = items.Sum(); // total = 15 |
List of objects
For the purpose of the article we need to create example class called Fruit containing two properties: Name and Price.
1 2 3 4 5 |
public class Fruit { public string Name { get; set; } public decimal Price { get; set; } } |
Now let’s create a list of fruits.
1 2 3 4 5 6 7 8 |
var fruits = new List<Fruit>() { new Fruit() { Name = "Orange", Price = 4.5M }, new Fruit() { Name = "Pear", Price = 2.9M }, new Fruit() { Name = "Apple", Price = 1.8M }, new Fruit() { Name = "Lemon", Price = 2.1M }, new Fruit() { Name = "Banana", Price = 2.7M } }; |
If we want to calculate total price off all fruits from the list we need to use Sum function and define a selector which is passed as a first argument.
1 |
var total = fruits.Sum(x => x.Price); // total = 14.0 |