Jul 25

How to: Get the Sum of the Values from List in C#.Net?

How to: Get the Sum of the Values from List in C#.Net?

Currently I am working on a new project in which I need to calculate some statistics that involve some basic statistics which require the total amount. The easy way out is just to do a foreach statement and iterate through the list adding the values. But somehow, I wanted something that looked fancier but really cleaner and much easier to maintain and understand. Because of that, I came across the Sum method found in a list. In my case, because I was obtaining all the data from an API and it was returned in a Json… it came as a string. So adding the complexity of adding a list of object’s string properties.

In order to achieve the end result: “Summing all string representations of numbers stored as properties in a list of objects in a clean, easy to manage way” we rely on LINQ:

decimal total = myListOfValues.Sum(x => decimal.Parse(x.NumberAsString));

and just like that, we’ve got our numbers all summed up in just one simple line!

Leave a Reply

%d bloggers like this: