Reputation: 5223
I have this class that i want to pass to my view:
public class AggregateProductionTotals
{
public int TotalPieces { get; set; }
public int TotalPallets { get; set; }
}
I generate my list with:
var dailyProductionGroup = dailyProduction
.OrderBy(o => o.F61Bprod.WPKYFN)
.GroupBy(g => new { g.F61Bprod.WPKYFN, g.F61Bprod.WPDOCO })
.Select(g => new AggregateProduction
{
LineCode = g.Key.WPKYFN,
ItemCode = g.Max(i => i.JdeItemBasic.litm),
ItemDescriptionEnglish = g.Max(i => i.JdeItemBasic.dsce),
ItemDescriptionLocal = g.Max(i=>i.JdeItemBasic.dsc),
WorkOrder = g.Key.WPDOCO,
NumberOfPallets = g.Count(),
TotalPiecesOrUnits = g.Sum(s=>(int)s.F61Bprod.WPTRQT),
AvergaWeight = g.Average(a=>Convert.ToInt32(a.F61Bprod.WPLOT2))
});
I want to calculate the totals for two of the fields and put them in a new class. I currently do it like this:
int totalPallets = 0;
int totalPiecesOrUnits = 0;
foreach (var item in dailyProductionGroup)
{
totalPallets += item.NumberOfPallets;
totalPiecesOrUnits += item.TotalPiecesOrUnits;
}
and then i create the class when i return the view.
How i replace the foreach with a simple LINQ to return my class?
Upvotes: 1
Views: 126
Reputation: 460068
Use Enumerable.Sum
var procutionTotals = new AggregateProductionTotals
{
TotalPallets = dailyProductionGroup.Sum(i => i.NumberOfPallets),
TotalPieces = dailyProductionGroup.Sum(i => i.TotalPiecesOrUnits)
};
Upvotes: 1