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

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

Patricia Arquette
Release: 2025-01-09 07:21:43
Original
764 people have browsed it

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

Efficiently Summing Object Properties in C# Lists using LINQ

This guide demonstrates how to calculate the sum of a specific numeric property within a C# list of objects using LINQ's Sum() method. Let's say you have a list where each object contains a numerical property, for example, "Amount". A common mistake is attempting to directly access the property like myList.amount.Sum(). This is incorrect.

The correct approach utilizes a lambda expression for concise and efficient summation:

<code class="language-csharp">using System.Linq;

// ... your code ...

double total = myList.Sum(item => item.Amount);</code>
Copy after login

The lambda expression item => item.Amount elegantly maps each object (item) in the myList to its Amount property. The Sum() method then efficiently calculates the total of these values. This avoids manual iteration, resulting in cleaner and more readable code.

The above is the detailed content of How to Calculate the Sum of an Object Property in a C# List Using LINQ?. 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