Using LINQ to sum up a list of numbers
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.
Subscribe for Free
Want to stay ahead of the curve? Subscribe now to receive the latest updates, actionable insights, and thought-provoking ideas around business, technology, and leadership straight to your inbox.