【问题标题】:Using GroupBy, Count and Sum in LINQ Lambda Expressions在 LINQ Lambda 表达式中使用 GroupBy、Count 和 Sum
【发布时间】:2011-03-25 18:03:36
【问题描述】:

我有一组具有重量、体积和所有者属性的盒子。

我想使用 LINQ 获取框信息的汇总列表(按所有者)

例如

**Owner, Boxes, Total Weight, Total Volume**  
Jim,     5,     1430.00,      3.65  
George,  2,     37.50,        1.22

谁能告诉我如何使用 Lambda 表达式来做到这一点?

【问题讨论】:

    标签: linq count lambda group-by sum


    【解决方案1】:
        var ListByOwner = list.GroupBy(l => l.Owner)
                              .Select(lg => 
                                    new { 
                                        Owner = lg.Key, 
                                        Boxes = lg.Count(),
                                        TotalWeight = lg.Sum(w => w.Weight), 
                                        TotalVolume = lg.Sum(w => w.Volume) 
                                    });
    

    【讨论】:

      【解决方案2】:
              var q = from b in listOfBoxes
                      group b by b.Owner into g
                      select new
                                 {
                                     Owner = g.Key,
                                     Boxes = g.Count(),
                                     TotalWeight = g.Sum(item => item.Weight),
                                     TotalVolume = g.Sum(item => item.Volume)
                                 };
      

      【讨论】:

        【解决方案3】:
        var boxSummary = from b in boxes
                         group b by b.Owner into g
                         let nrBoxes = g.Count()
                         let totalWeight = g.Sum(w => w.Weight)
                         let totalVolume = g.Sum(v => v.Volume)
                         select new { Owner = g.Key, Boxes = nrBoxes,
                                      TotalWeight = totalWeight,
                                      TotalVolume = totalVolume }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-27
          • 1970-01-01
          相关资源
          最近更新 更多