1

我有这个类,我想传递给我的视图:

public class AggregateProductionTotals
{
    public int TotalPieces { get; set; }
    public int TotalPallets { get; set; }
}

我生成我的列表:

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))
                                 });

我想计算两个字段的总数并将它们放入一个新类中。我目前这样做:

            int totalPallets = 0;
            int totalPiecesOrUnits = 0;
            foreach (var item in dailyProductionGroup)
            {
                totalPallets += item.NumberOfPallets;
                totalPiecesOrUnits += item.TotalPiecesOrUnits;
            }

然后我在返回视图时创建类。

我如何用简单的 LINQ 替换 foreach 以返回我的课程?

4

1 回答 1

1

利用Enumerable.Sum

var procutionTotals = new AggregateProductionTotals
{
    TotalPallets = dailyProductionGroup.Sum(i => i.NumberOfPallets),
    TotalPieces  = dailyProductionGroup.Sum(i => i.TotalPiecesOrUnits)
}; 
于 2013-09-30T07:06:22.577 回答