Home >Backend Development >C++ >How to Calculate the Sum of a Property in a C# List of Objects Using LINQ?

How to Calculate the Sum of a Property in a C# List of Objects Using LINQ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-08 22:56:42197browse

How to Calculate the Sum of a Property in a C# List of Objects Using LINQ?

Efficiently Summing Properties in C# Object Lists with LINQ

Working with collections of objects frequently requires aggregating data from individual elements. A common task is calculating the sum of a specific property across all objects. C#'s LINQ (Language Integrated Query) provides an elegant solution.

Leveraging LINQ's Sum() Method

LINQ's Sum() method offers a concise way to achieve this. Instead of attempting direct access like myList.amount.Sum(), which is syntactically incorrect, use the following LINQ expression:

Example:

To sum the "amount" property from a list of objects, use:

<code class="language-csharp">double total = myList.Sum(item => item.Amount);</code>

Explanation:

  • myList: Your list of objects.
  • Sum(): The LINQ aggregate function that calculates the sum of numeric values in a sequence.
  • item => item.Amount: A lambda expression that selects the Amount property from each item in the myList.

This single line efficiently computes the total sum of the Amount property. This approach is far more readable and maintainable than manual iteration.

The above is the detailed content of How to Calculate the Sum of a Property in a C# List of Objects Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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