C# List of Objects, How to Get the Sum of a Property

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

using System.Linq;

...

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

C# Sum Object List on specific property

You can simply use a GroupBy and project the results

Groups the elements of a sequence.

Example

var results = List.GroupBy(x => x.name)
.Select( x => new { name = x.Key, val = x.Sum(x => x.val) });

Calculate SUM of a property in list

In order to calculate a sum, use Sum:

SummaryList.Add(new ActivitySummary() {
Name = "TOTAL",
Marks = SummaryList.Sum(item => Convert.ToInt32(item.Marks)).ToString()
});

If your Marks property only contains integer numbers, making it of type string makes no sense. You can simplify the query if it is of type int:

public class Summary
{
public string Name { get; set; }
public int Marks { get; set; }
}

SummaryList.Add(new ActivitySummary() {
Name = "TOTAL",
Marks = SummaryList.Sum(item => item.Marks)
});

If your Marks property is not an integer number, use decimal, float or double instead of int (and Convert.ToDecimal, Convert.ToSingle and Convert.ToDouble respectively).

c# array of objects how to sum object.a property based on object.b property

You have forgotten that a Where expression receives the current item in the sequence enumerated. So it should be Where(x => x.b != null) but you need also to tell the Sum expression what you want to sum. The Select part is not needed at all.

So, assuming b is a nullable type (IE int? b {get;set;}) then you can get the sum of a where b is null in a simple way

var result = objectArray.Where(x => x.b != null).Sum(k => k.a);

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

Sum List T Properties of each item in List T

As I understand the question you look for something like this:

var results = list.Select((m, i) => new 
{
m.Name,
Value = list.Sum(t => t.SubObj[i].Value)
}).ToList();

This creates a list of an anonymous type containing the name of each main object and the sum of all subobject values with the same index as the main object.


It's not clear from your question, but if you want to sum all subojects (not only as many as there are main objects), you can do it like this:

var results = Enumerable.Range(0, list[0].SubObj.Count)
.Select(i => list.Sum(m => m.SubObj[i].Value)).ToList();

This gives you a list of the sums (without names, as your examples suggest that you "don't really care" about any names).

How to get Sum from List in another List as a property with linq

You can achieve it couple of ways

Option 1

double _sum =_listMaster.Where(f => f.IsActive)
.Sum(x=>x._detail.Sum(c=>c.Price * c.Quantity));

Option 2

double _sum =_listMaster.Where(f => f.IsActive)
.Aggregate(0d,(result,item)=>result + item._detail.Sum(x=>x.Price * x.Quantity));

Option 3

double _sum =_listMaster.Where(f => f.IsActive)
.SelectMany(x=>x._detail)
.Sum(x=>x.Price * x.Quantity);

How to get the sum of List object property values using foreach

If you want to increment PriceSum variable with product price, use += operator:

foreach (var ProductsInCart in _cartList)
{
PriceSum += ProductsInCart.Price; // instead of =+
}

When you write = +value then its two separate operators = operator and + operator i.e. +ProductsInCart.Price just returns value of products, price, and then you assign this value to PriceSum. As result, you will have price of last product in list.

You also can use LINQ instead of this loop:

public float PriceAllContent
{
get { return _cartList.Sum(p => p.Price); }
}

How to calculate sum for specific property without grouping main list data

  1. Fetch all the invoices from the database:

    var invoices = await _dbContext.Invoices
    .Where(p => p.CheckDate >= startDate && p.CheckDate <= endDate)
    .ToListAsync();
  2. Group the in-memory results using Linq-To-Object:

    var result = invoices?
    .GroupBy(p => new { p.CompanyId, p.PackageId, p.BankId, p.PayMethod })
    .SelectMany(x => x.Select(y =>
    new DemoDto
    {
    CompanyId = y.CompanyId,
    Title = y.Title,
    Price = y.Price,
    Total = x.Sum(z => z.Price)
    }))
    .ToList();

If you want to perform the grouping in the database for some reason, you should execute a raw SQL query or a stored procedure rather than relying on the ORM to generate some magic (and most probably inefficient) query for you.

Is it possible to use LINQ to sum the value of multiple objects in a new object

You need to update three properties, so having "one-liner" will make code very unreadable.

If asking about different LINQ approach instead of summarising three values, then Aggregate is your choice, check @Andy's answer.

If you wrap logic with the method then you can use any amount of lines inside the implementation, but keep it one-liner for the consumers.

Alternative approach can be an extension method for enumerable

public static MyObject CalculateSum(this IEnumerable<MyObject> objects)
{
var total = new MyObject();
foreach (var obj in objects)
{
total.MyProperty1 += obj.MyProperty1;
total.MyProperty2 += obj.MyProperty2;
total.MyProperty3 += obj.MyProperty3;
}

return total;
}

Usage is "one-liner" :)

var objects = new MyObject[] { myObject1, myObject2, myObject3 };

var sum = objects.CalculateSum();

Notice that all LINQ methods are extension methods, so you kinda using your own domain specific LINQ "one-liner" ;)



Related Topics



Leave a reply



Submit