Sum
How do you sum up all the numbers in an array or list? With linq, we can use the .Sum
method.
Basic example
Live example: https://dotnetfiddle.net/tvUKY5
var scores = new[] { 87, 56, 33, 20, 11, -10, -50 };
int totalScores = scores.Sum();
// output: 147
Sum with Func
If you ever need to perform a summation of numbers but also need to perform a transformation on each number before the summation, then you can use the Sum
with a Func
.
The example below performs a division of 100 to each number - this is shown in the lambda expression i => i/100d
Live example: https://dotnetfiddle.net/dt0EJN
var scores = new[] { 87, 56, 33, 20, 11, -10, -50 };
// divide each number by 100 before summing.
double sum = scores.Sum(i => i/100d);
// output 1.47