Using GroupBy, Count and Sum in LINQ Lambda Expressions

前端 未结 3 720
星月不相逢
星月不相逢 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 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 }
    

提交回复
热议问题