使用LINQ而不是foreach从IEnumerable计算总计

时间:2013-09-30 07:00:25

标签: linq running-total totals

我有这个课,我想传递给我的观点:

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以返回我的课程?

1 个答案:

答案 0 :(得分:1)

使用Enumerable.Sum

var procutionTotals = new AggregateProductionTotals
{
    TotalPallets = dailyProductionGroup.Sum(i => i.NumberOfPallets),
    TotalPieces  = dailyProductionGroup.Sum(i => i.TotalPiecesOrUnits)
};