Home > Backend Development > C++ > How to Sum a Property's Values from a List of Objects in C#?

How to Sum a Property's Values from a List of Objects in C#?

Patricia Arquette
Release: 2025-01-09 06:32:42
Original
478 people have browsed it

How to Sum a Property's Values from a List of Objects in C#?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template