代码之家  ›  专栏  ›  技术社区  ›  e4rthdog

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

  •  1
  • e4rthdog  · 技术社区  · 12 年前

    我有一个类,我想把它传给我的视图:

    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 回复  |  直到 4 年前
        1
  •  1
  •   Tim Schmelter    12 年前

    使用 Enumerable.Sum

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