6.04.2010

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.

[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.

[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

1 comments:

  1. We need a new `new` keyword: `old`. Yoda, young he is not.
    ReplyDelete