Home >Backend Development >C++ >How to Calculate the Sum of a Property in a C# List of Objects?
Summing a Property in a C# List of Objects: A Simple Guide
Working with lists of custom objects often necessitates calculating the sum of a particular property across all objects. This tutorial demonstrates how to efficiently achieve this using C#'s LINQ capabilities.
Steps:
Include the LINQ Namespace:
Begin by importing the necessary namespace:
<code class="language-csharp">using System.Linq;</code>
Employ the Sum()
Extension Method:
The Sum()
method, part of LINQ, provides a concise way to sum values. For object lists, a lambda expression selects the property to be summed.
<code class="language-csharp">double total = myList.Sum(item => item.PropertyToSum);</code>
Replace myList
with your list of objects and PropertyToSum
with the name of the property you wish to sum. The lambda expression item => item.PropertyToSum
extracts the specified property value from each object.
Store the Result:
The Sum()
method returns a double
representing the total. Assign this to a variable (e.g., total
) for further use.
This streamlined approach simplifies summing object properties, enabling efficient data aggregation within your C# applications.
The above is the detailed content of How to Calculate the Sum of a Property in a C# List of Objects?. For more information, please follow other related articles on the PHP Chinese website!