How to use the C# LINQ Sum function to sum up values in 2024

C# LINQ Sum function for summing up values
C# LINQ Sum function for summing up values

Summing up values with the C# LINQ Sum function is easily done by providing for example a lambda expression. Just call it with our without a lambda on your „IEnumerable“ implementing instance like „theIntegers.Sum()“. It’s a bit more complicated, if you actually have some more complex object like a bill or if you want to sum up more properties at once.

Why you should (could) use the C# LINQ Sum function?

Every developer – and I really mean that – will need to have some sort of summing up functionality at some time. Imagine like a billing software not being able to sum up your costs (or your gains on the other side 🤭). There is pretty much the old way – which you will see in a few seconds – and the newer way, which is much more convenient.

Usually you would do this like the following manual steps – meaning „the old way“:

  • Create some sort of „sum“ storage / variable
  • Take the list (enumerable)
  • Go through each element
  • Increment the sum storage thingy
  • After all iterations, you will have your result

The „old“ way of summing up things in for example C#

Represented by some code (and it pretty much doesn’t matter in which language) it would look like the following. For our first example, I will simply use a little list of integers:

var numbers = new List<int>() { 1, 2, 5 };
var sum = 0;
foreach (var number in numbers) {
  sum += number;
}
// you'll have the total sum here

As you can see, this is some sort of repeating code which you could create over and over. Sure, a slightly advanced developer will notice pretty fast, that this is a bad code smell. So what are we going to do?

Improving and grouping the functionality

We need some way of grouping that „sum up“ functionality into a small block of functionality. You might have guessed it – we could use a function in the first place. It could be even better by using a separate class with an instance method, to make it more testable, but I’ll leave it like the following for now.. Let’s call it SumUp:

public static int SumUp(IEnumerable<int> numbers)
{
  var sum = 0;
  foreach (var number in numbers) {
    sum += number;
  }
  return sum;
}

Now you could easily reuse the block by calling the function, instead of writing the same few lines again and again:

// you'll have your list over here, again..
var sum = SumUp(numbers);

Sure, you could make this more generic and therefore more reusable as well, but we will skip this for now. I think you already got the point over here.

But, isn’t there a better way?

Now, you could ask yourself: „Well, if this is some basic functionality each developer needs from time to time, isn’t there some existing tool for this“. And I can totally say: „Yup, there is!“. It is even available for different datatypes (generic) and more. I’m talking about the C# LINQ Sum extension method / function.

How to use the C# LINQ Sum extension function?

How to use the C# LINQ Sum function
How to use the C# LINQ Sum function?

After getting to know how our task of summing up values would be implemented manually and knowing that there’s a basic tool, we’ll take a closer look. How could we now actually use the sum extension method?

Summing up a simple list of like integers

Reusing the list of numbers from above, we might now use the sum function as follows. First, take the variable name of your List of integers (for example) and then use the function on that. If the sum method isn’t appearing in like your code autocompletition, just make sure you have imported the right namespace called „System.Linq“.

// dont forget the using/import of System.Linq
// re-initializing a list of ints called numbers (again)
var numbers = new List<int>() { 1, 2, 5 };
var sum = numbers.Sum();

But what if I have more complex objects?

The above example works pretty nice, if you only have a simple list of like integers or even decimals. But how can you actually implement this for a more complex scenario, e.g. when working with objects like bills. We will take a look at this in the next section, but first, we need to create some sort of class for this.

class Bill
{
  
  // I've omitted other unnecessary properties, etc. for this example

  public decimal GrossValue { get; set; }

  public Bill(decimal grossValue)
  {
    GrossValue = grossValue;
  }

}

Now let’s create some bill instances and sum up their values using the C# LINQ Sum extension function:

var bills = new List<Bill>();
bills.Add(new Bill(14.95M));
bills.Add(new Bill(9.95M));
bills.Add(new Bill(5M));
var sum = bills.Sum(bill => bill.GrossValue);

What you will notice now is, that we are using a lambda functionality to provide the value to be summed by the sum function (woah, sorry for that sentence.). But lemme guess, next you could possibly have this question: „Okay, but how can I now sum up multiple values at once?“.

Summing up multiple values at once

Seeing the example from above, you probably noticed, that we can only provide one value to be summed up. But don’t worry, we can easily sum up multiple values at once, by just changing our code a little bit. We will be using the LINQ extensions for this as well:

var bills = new List<Bill>();
bills.Add(new Bill(119, 100));
bills.Add(new Bill(119, 100));
var sums = bills
    .GroupBy(x => 1)
    .Select(b => new
    {
      TotalGross = b.Sum(x => x.GrossValue),
      TotalNet = b.Sum(x => x.NetValue)
    })
    .FirstOrDefault();
// now you could use sums.TotalGross or sums.TotalNet
// check sums for null, if there could be no items inside the bills list resulting in a null return value

Here, we are taking the bills and we’re grouping them on a common constant, this will help us using the „sum“ on the „sub-items“. After the grouping, we then need to select a new object creating a common store for both properties on an anonymous object instance. In the last step, we are using the „FirstOrDefault“ function, because using „Select“ on the grouping would return an „IEnumerable“ otherwise..

Summing up (pun intended)

C# LINQ Sum function - Summing up
C# LINQ Sum function – Summing up

So at the end of this post I showed you, how you can use the C# LINQ Sum extension method to sum up different things. At first, we took a look at the older way of doing this manually and then we created a reusable function on our own. Next, we switched to the already existing sum extension methods to sum up a simple list of numbers in the first place. In the last two steps, we dived deeper with summing up complex objects and even multiple properties / columns as well.

Related posts

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert