Using GroupBy, Count and Sum in LINQ Lambda Expressions

前端 未结 3 662
星月不相逢
星月不相逢 2020-12-04 13:34

I have a collection of boxes with the properties weight, volume and owner.

I want to use LINQ to get a summarized list (by owner) of the box information

e.g.

相关标签:
3条回答
  • 2020-12-04 13:37
        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) 
                                    });
    
    0 讨论(0)
  • 2020-12-04 14:01
    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 }
    
    0 讨论(0)
  • 2020-12-04 14:03
            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)
                               };
    
    0 讨论(0)
提交回复
热议问题