C# List of objects, how do I get the sum of a property

c# list sum group by
c# linq sum values in list
c# sum = list of int
sum in lambda expression c
c# sum of array
c# sum list of doubles
get sum of list c#
c# sum list of decimals

I have a list of objects. One property of the individual object entry is amount. How do I get the sum of amount?

If my list was of type double I may be able to do something like this:

double total = myList.Sum();

However I want to something similar to this, yet this syntax is incorrect.

double total = myList.amount.Sum();

How should I go about accomplishing this? I would love to use the Sum function if possible instead of looping through and calculating the value.

using System.Linq;

...

double total = myList.Sum(item => item.Amount);

C# List of objects, how do I get the sum of a property, Gets sum of values from list of integer numbers. var numbers LINQ query expression to get sum of numeric values in the collection. var list� Then if you have a list of Summary objects (In your example called SummaryList), you can calculate a sum like this: You will have to use.Select()in order to isolate an IEnumerable containing all Marks in a list. Afterwards, you can use.Sum()in order to sum up all these values. double sum = SummaryList.Select(x => x.Marks).Sum();

And if you need to do it on items that match a specific condition...

double total = myList.Where(item => item.Name == "Eggs").Sum(item => item.Amount);

c# - How to get sum of the values from List?, It computes the sum total of all the numbers in an array, or List, of integers. Tip: The method can be used on objects that implement IEnumerable with a type of overhead that will make it slower than a simple for-loop in the C# language. the Sum extension, as well as some overloads you can use. Home. Dot Net Perls. I know we can do it using for, but want to know if there are any better ways to get this using linq query because that reduces lines of code and I have similar requirements in many other places and dont want to write number of foreach or fors every time.

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

LINQ Sum, list.AsQueryable().Sum();. The following is an example to find the sum of elements of a list with integer elements. Example. Live� C#. List<float> numbers = new List<float> { 43.68F, 1.25F, 583.7F, 6.5F }; float sum = numbers.Sum (); Console.WriteLine ("The sum of the numbers is {0}.", sum); /* This code produces the following output: The sum of the numbers is 635.13. */. ' Create a list of Single values.

Here is example code you could run to make such test:

var f = 10000000;
var p = new int[f];

for(int i = 0; i < f; ++i)
{
    p[i] = i % 2;
}

var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);

int x = 0;
time = DateTime.Now;
foreach(var item in p){
   x += item;
}
Console.WriteLine(DateTime.Now - time);

x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
   x += p[i];
}
Console.WriteLine(DateTime.Now - time);

The same example for complex object is:

void Main()
{
    var f = 10000000;
    var p = new Test[f];

    for(int i = 0; i < f; ++i)
    {
        p[i] = new Test();
        p[i].Property = i % 2;
    }

    var time = DateTime.Now;
    p.Sum(k => k.Property);
    Console.WriteLine(DateTime.Now - time);

    int x = 0;
    time = DateTime.Now;
    foreach(var item in p){
        x += item.Property;
    }
    Console.WriteLine(DateTime.Now - time);

    x = 0;
    time = DateTime.Now;
    for(int i = 0, j = f; i < j; ++i){
        x += p[i].Property;
    }
    Console.WriteLine(DateTime.Now - time);
}

class Test
{
    public int Property { get; set; }
}

My results with compiler optimizations off are:

00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)

and for second test are:

00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()

it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

C# Sum Method: Add up All Numbers, You can use the Sum function public int HintsUsed => questions.Sum(q => q. hintsUsed);. By using an expression bodied member (since C#� Enumerable.Sumis extension method from System.Linqnamespace. It returns sum of numeric values in collection. Sum for Numeric Types Gets sum of values from list of integer numbers.

C# Linq Sum() Method, Represents a strongly typed list of objects that can be accessed by index. C# Copy. public class List<T> : System.Collections.Generic.ICollection<T>, System. The default Item[] property (the indexer in C#) is used to retrieve an item, the been less than 10 percent of total capacity, the list would not have been resized. C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property. The following example will produce the same result as the example above. The only difference is that there is less code:

adding properties together from list of objects using LINQ, C# Copy. public static int? Sum (this System.Collections.Generic. A sequence of nullable Int32 values to calculate the sum of. This method returns zero if source contains no elements. The result does not include values List<float> numbers = new List<float> { 43.68F, 1.25F, 583.7F, 6.5F }; float sum = numbers. Sum();� C# Sum Method: Add up All Numbers Use the Sum extension method and the selector overload. Include the System.Linq namespace.

List<T> Class, Count Property is used to get the total number of elements contained in the List. Properties: It is different from the arrays. A list can be resized� The following diagram illustrates the List<T> hierarchy. As shown in the above diagram, the List<T> class implements eight different interfaces that provide different functionalities. Hence, the List<T> object can be assigned to any of its interface type variables.

Comments
  • Is this quicker than foreach out of interest?
  • I am also interested in @CodeBlend's question. Will this computation be faster than a for loop?
  • @Coops - To answer your question...using a list containing 100,000 objects, each object having a single property of datatype double, summing up the property 1,000 times using solution above (myList.Sum) takes 2.44 seconds compared to 0.98 seconds using foreach. The elapsed time is measured using the Stopwatch class for accuracy. Therefore foreach is over 2x faster than using myList.Sum.
  • Instead of .Select(i => i.Moons).Sum() you can use .Sum(i => i.Moons)
  • @Mason, right and that is how Alex approached the problem in his earlier answer, so I just provided a different way of doing the same thing.
  • Ah yes, sorry for my misconception.
  • I appreciate that this is a unique answer, but wouldn't performance suffer?
  • for future reference, have a look at Stopwatch in System.Diagnostics as it is a high-performance time recorder. (I didn't downvote you btw)
  • Do not use DateTime.Now for measuring. It has terrible performance as it returns always local time. DateTime.UtcNow is faster; however, it still does not use as high resolution as the Stopwatch class.
  • This does not answer the question.
  • Ok, thanks for tip. Score's are very repeatable so I assumed that such resolution is enough
  • While your intention is good -Mark is right- you're not explicitly answering the question. I'd recommend you change it to: "Here is how you could do it" and "Here is the cpu performance of each option". Also in principle if you describe your testing methodology you need-not show us the code.