Summing Object Properties in C# Lists: A Concise Guide
Frequently, C# developers need to calculate the sum of a specific property within a list of objects. While Sum()
readily handles primitive types like double
, object properties require a slightly different approach.
Let's say you have a list of objects, each possessing an "Amount" property. Simply using myList.amount.Sum()
is incorrect.
The correct method leverages LINQ's Sum()
with a lambda expression:
<code class="language-csharp">double total = myList.Sum(item => item.Amount);</code>
Explanation:
myList
: Your list of objects..Sum(...)
: The LINQ extension method that iterates, applies a function, and sums the results.item => item.Amount
: A lambda expression. For each item
in myList
, it extracts the Amount
property.total
: The variable storing the final sum.This efficiently iterates through the list, accesses each object's Amount
property, and calculates the total.
The above is the detailed content of How to Calculate the Sum of an Object Property in a C# List?. For more information, please follow other related articles on the PHP Chinese website!