Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GroupBy, Count and Sum in LINQ Lambda Expressions

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?

like image 779
Jimbo Avatar asked Aug 05 '10 11:08

Jimbo


People also ask

What does => mean in LINQ?

The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.

How does GroupBy work LINQ?

Group by works by taking whatever you are grouping and putting it into a collection of items that match the key you specify in your group by clause.

Is LINQ faster than lambda?

There is no performance difference between LINQ queries and Lambda expressions.


2 Answers

    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)                                  }); 
like image 100
bodee Avatar answered Oct 03 '22 02:10

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)                            }; 
like image 32
jeroenh Avatar answered Oct 03 '22 01:10

jeroenh