Using GroupBy, Count and Sum in LINQ Lambda Expressions

162,237

Solution 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) 
                                });

Solution 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)
                           };

Solution 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 }
Share:
162,237

Related videos on Youtube

Jimbo
Author by

Jimbo

Updated on July 05, 2022

Comments

  • Jimbo
    Jimbo almost 2 years

    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.

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

    Can someone show me how to do this with Lambda expressions?