How to calculate the sum of attributes in an object list in C#?
Calculating the sum of a specific property is a common need when working with lists of objects. C# provides the Sum function for arrays and lists, which makes it easy to calculate aggregate values.
To illustrate the use of Sum in objects, consider the following scenario:
Given a list of objects, each of which contains an Amount property, how do you retrieve the total amount using the Sum function?
Grammar issues
Trying to use myList.amount.Sum()
will result in a syntax error. The reason is that the property amount cannot be accessed directly from the list itself. Instead, you need to specify a delegate or lambda expression to access the Amount property of each object in the list.
Solution
To solve this problem, you can use a lambda expression to extract the Amount property of each object in the list, and then apply the Sum function to the resulting collection of numeric values. Here is an example:
<code class="language-csharp">using System.Linq; ... double total = myList.Sum(item => item.Amount);</code>
In this example, the lambda expression item => item.Amount
retrieves the Amount property of each item in myList
. The Sum function then applies a sum operation to the extracted set of Amount values, effectively calculating the total amount.
The above is the detailed content of How to Sum a Property's Values from a List of Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!