Note: This article was originally published in 2016. Some steps, commands, or software versions may have changed. Check the current C# documentation for the latest information.
In this step-by-step guide, you’ll learn 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!
Summary
You’ve successfully learned get the sum of the values from list in c#.net?. If you run into any issues, double-check the prerequisites and ensure your C# environment is properly configured.