Efficiently Summing Object Properties in C# Lists using LINQ
This guide demonstrates how to calculate the sum of a specific numeric property within a C# list of objects using LINQ's Sum()
method. Let's say you have a list where each object contains a numerical property, for example, "Amount". A common mistake is attempting to directly access the property like myList.amount.Sum()
. This is incorrect.
The correct approach utilizes a lambda expression for concise and efficient summation:
<code class="language-csharp">using System.Linq; // ... your code ... double total = myList.Sum(item => item.Amount);</code>
The lambda expression item => item.Amount
elegantly maps each object (item
) in the myList
to its Amount
property. The Sum()
method then efficiently calculates the total of these values. This avoids manual iteration, resulting in cleaner and more readable code.
The above is the detailed content of How to Calculate the Sum of an Object Property in a C# List Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!