Home >Backend Development >C++ >How to Calculate the Sum of an Object Property in a C# List?

How to Calculate the Sum of an Object Property in a C# List?

Susan Sarandon
Susan SarandonOriginal
2025-01-09 06:16:42289browse

How to Calculate the Sum of an Object Property in a C# List?

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!

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