web-dev-qa-db-ja.com

LINQ Lambda式でのGroupBy、Count、およびSumの使用

プロパティweight、volume、およびownerを持つボックスのコレクションがあります。

LINQを使用して、ボックス情報の要約リスト(所有者別)を取得したい

例えば.

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

誰かがラムダ式でこれを行う方法を教えてもらえますか?

75
Jimbo
    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) 
                                });
152
bodee
        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)
                           };
13
jeroenh
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 }
6