I have code similar to this:
decimal total1 = 0;
decimal poTotal = 0;
foreach( var record in listOfRecords)
{
total1 += record.Price;
if ( record.HasPo){
poTotal += record.PoTotal;
}
}
This works fine but I'd like to know how to perform multiple aggregates using linq without excessive coding for groups etc... is there a simple way that doesn't require scanning the list of objects each time?
I know I could do this:
var poTotal = listOfRecords.Where(r=> r.HasPo).Sum(r.PoTotal);
But that requires scanning the entire list and I if I'm to aggregate multiple values I only want to loop/scan one time.
You can use Aggregate
method, but I don't think it will be more clear than a simple foreach
loop you already have:
var totals = listOfRecords.Aggregate(
new { Total = 0m, PoTotal = 0m },
(a, r) => new {
Total = a.Total + r.Price,
PoTotal = a.PoTotal + (r.HasPo ? r.PoTotal : 0m)
});
Console.WriteLine(totals.Total);
Console.WriteLine(totals.PoTotal);
You could also do something like this:
decimal poTotal = 0;
decimal total = listOfRecords.Sum(record => {
if (record.HasPo) {poTotal += record.PoTotal;}
return record.Price;
});
But I'm not saying you should . As MarcinJurasek says, the simple foreach
is clearest in this case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.