Skip to content

Using LINQ to sum up a list of numbers

Robert Greiner
Robert Greiner
2 min read

I don't really like foreach loops. They are difficult to read and easy to abuse.

Let's say, for example that we want to sum up the following list of numbers:

private int[] numberList = {1, 2, 4, 8, 16, 32}; //sum = 63

Conventional programming wisdom says that we should do the following to find the sum of the above list:

int sum = 0;
foreach (int num in numberList)
{
    sum += num;
}

While this code does exactly what we need, it is not very expressive in its form. foreach loops end up looking the same whether you are trying to find the sum of a set of numbers or searching through a list of users to find a random contest winner.

Luckily for us, .NET provides a easier and more readable way to accomplish the same functionality as the foreach loop above.

We will sum the same list of numbers using both a foreach loop and a LINQ expression. First, let's start off with some tests so we know what we can set up our expectations early.

public class SumNumbersTests
{
  [Test]
  public void ShouldAddAllValuesUsingForeach()
  {
    var sum = new SumNumbers();
    Assert.AreEqual(63, sum.SumUsingForeach());
  }

  [Test]
  public void ShouldAddAllValuesUsingLinqExpression()
  {
    var sum = new SumNumbers();
    Assert.AreEqual(63, sum.SumUsingLinq());
  }

  [Test]
  public void LinqExpressionAndForeachSumShouldBeEqual()
  {
    var sum = new SumNumbers();
    Assert.AreEqual(sum.SumUsingForeach(), sum.SumUsingLinq());
  }
}

Now that we have our tests set up, we can move on to the actual code.

public class SumNumbers
{
  private int[] numberList = {1, 2, 4, 8, 16, 32}; 

  public int SumUsingLinq()
  {
    return numberList.Sum(num => num);
  }

  public int SumUsingForeach()
  {
    var sum = 0;
    foreach (int num in numberList)
    {
      sum += num;
    }
    return sum;
  }
}

See how much easier the LINQ expression is to read? In fact, you don't even need to put anything in the parenthesis.

public int SumUsingLinq()
{
  return numberList.Sum();
}

Taking it to the next level

The above example was a bit simple, so let's solve a problem that is a little more complex to help drive the point home. Let's say that we want to sum the squares of each item in numberList.

Just as before, we can manually find our expected answer given the same list of integers and set up our expectation before writing our production code.

[Test]
public void ShouldSumTheSquaresOfAllValuesUsingLinqExpression()
{
  var sum = new SumNumbers();
  Assert.AreEqual(1365.0, sum.SumSquaresUsingLinq());
}

Now, we can use the same methods as above which becomes more readable and succinct.

public double SumSquaresUsingLinq()
{
  return numberList.Sum(num => Math.Pow(num, 2));
}

You can find the project files for this example on Github under the Open Source Public License.

Please consider subscribing, it's free.
Technology

Robert Greiner Twitter

Professional optimist. I write a weekly newsletter for humans at the intersection of business, technology, leadership, and career growth.


Related Posts

Members Public

AI Rule #1 - Customer First

In 1985, Warren Buffett wisely said, "The first rule of investment is don't lose. And the second rule of investment is don't forget the first rule, and that's all the rules there are." Similarly, the first rule of AI investment is to

AI Rule #1 - Customer First
Members Public

Navigating the Upside Down as a Technology Leader

Ideas for leading technology organizations with confidence and creativity.

Navigating the Upside Down as a Technology Leader
Members Public

Artist for a Day

The future of creative output is multiplied by AI.

Artist for a Day