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

Joseph U. picture Joseph U. · Dec 4, 2010 · Viewed 217.1k times · Source

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.

Answer

Alex LE picture Alex LE · Dec 4, 2010
using System.Linq;

...

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