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

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-09 05:59:48235browse

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:

  1. Include the LINQ Namespace:

    Begin by importing the necessary namespace:

    <code class="language-csharp">using System.Linq;</code>
  2. 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.

  3. 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!

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