Jonathan Birkholz

Linq - Sum

Last week I started an ongoing section during the Virtual Brown Bag where I go over a Linq function (or two). The general idea is that although most people ‘use’ Linq, there are lots of functions that are overlooked.

In this blog post I will demonstrate basic usage cases for the Linq Sum function.

Numbers

If you have a collection of numbers and you want the sum of their values, then simply call Sum. It can’t get any easier.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Test]
public void should_sum_values()
{
var nums = new List<int>
{
5,
9,
1,
10
};
int sum = nums.Sum();
sum.ShouldBe(25);
}

Non-Numbers

If you want to sum a collection that isn’t made up of numbers, then you will be forced to specify which number property you would like to sum.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[Test]
public void summing_non_number_collection()
{
var jedi = new List<Jedi>
{
new Jedi("Yoda").MidichlorianCountIs(1000),
new Jedi("Anakin Skywalker").MidichlorianCountIs(3000),
new Jedi("Luke Skywalker").MidichlorianCountIs(1500),
new Jedi("Obi-wan Kenobi").MidichlorianCountIs(500),
};
// can't compile
//var sum = jedi.Sum();
}
[Test]
public void should_be_able_to_specify_property_to_sum()
{
var jedi = new List<Jedi>
{
new Jedi("Yoda").MidichlorianCountIs(1000),
new Jedi("Anakin Skywalker").MidichlorianCountIs(3000),
new Jedi("Luke Skywalker").MidichlorianCountIs(1500),
new Jedi("Obi-wan Kenobi").MidichlorianCountIs(500),
};
int sum = jedi.Sum(j => j.MidichlorianCount);
sum.ShouldBe(6000);
}

These tests can be found in my Learning Solution on GitHub and found in the Learning CSharp project : http://github.com/RookieOne/Learning

C#, Linq