C# List of objects, how do I get the sum of a property

C#ListSum

C# Problem Overview


I have a list of objects. One property of the individual object entry is amount. How do I get the sum of amount?

If my list was of type double I may be able to do something like this:

double total = myList.Sum();

However I want to something similar to this, yet this syntax is incorrect.

double total = myList.amount.Sum();

How should I go about accomplishing this? I would love to use the Sum function if possible instead of looping through and calculating the value.

C# Solutions


Solution 1 - C#

using System.Linq;

...

double total = myList.Sum(item => item.Amount);

Solution 2 - C#

And if you need to do it on items that match a specific condition...

double total = myList.Where(item => item.Name == "Eggs").Sum(item => item.Amount);

Solution 3 - C#

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

Solution 4 - C#

Here is example code you could run to make such test:

var f = 10000000;
var p = new int[f];

for(int i = 0; i < f; ++i)
{
    p[i] = i % 2;
}

var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);

int x = 0;
time = DateTime.Now;
foreach(var item in p){
   x += item;
}
Console.WriteLine(DateTime.Now - time);

x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
   x += p[i];
}
Console.WriteLine(DateTime.Now - time);

The same example for complex object is:

void Main()
{
	var f = 10000000;
	var p = new Test[f];
	
	for(int i = 0; i < f; ++i)
	{
		p[i] = new Test();
		p[i].Property = i % 2;
	}
	
	var time = DateTime.Now;
	p.Sum(k => k.Property);
	Console.WriteLine(DateTime.Now - time);
	
	int x = 0;
	time = DateTime.Now;
	foreach(var item in p){
		x += item.Property;
	}
	Console.WriteLine(DateTime.Now - time);
	
	x = 0;
	time = DateTime.Now;
	for(int i = 0, j = f; i < j; ++i){
		x += p[i].Property;
	}
	Console.WriteLine(DateTime.Now - time);
}

class Test
{
	public int Property { get; set; }
}

My results with compiler optimizations off are:

00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)

and for second test are:

00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()

it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoseph U.View Question on Stackoverflow
Solution 1 - C#Alex LEView Answer on Stackoverflow
Solution 2 - C#Greg QuinnView Answer on Stackoverflow
Solution 3 - C#usefulBeeView Answer on Stackoverflow
Solution 4 - C#PuchaczView Answer on Stackoverflow