Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroupBy in lambda expressions

Tags:

c#

lambda

linq

from x in myCollection
    group x by x.Id into y
    select new { 
       Id = y.Key, 
       Quantity = y.Sum(x => x.Quantity)
    };

How would you write the above as a lambda expression? I'm stuck on the group into part.

like image 746
fearofawhackplanet Avatar asked Sep 05 '25 17:09

fearofawhackplanet


2 Answers

Query continuations (select...into and group...into, but not join...into) are equivalent to just splitting up the query expression. So I like to think of your example as:

var tmp = from x in myCollection
          group x by x.Id;
var result = from y in tmp
             select new { 
               Id = y.Key, 
               Quantity = y.Sum(x => x.Quantity)
             };

Change those into dot notation:

var tmp = myCollection.GroupBy(x => x.Id);
var result = tmp.Select(y => new { 
               Id = y.Key, 
               Quantity = y.Sum(x => x.Quantity)
             });

Then you could combine them back:

var tmp = myCollection.GroupBy(x => x.Id)
                      .Select(y => new { 
                                Id = y.Key, 
                                Quantity = y.Sum(x => x.Quantity)
                              });

Once you work out what the C# compiler does with query expressions, the rest is relatively straightforward :)

like image 159
Jon Skeet Avatar answered Sep 07 '25 07:09

Jon Skeet


myCollection
    .GroupBy(x => x.Id)
    .Select(x => 
        new 
        { 
          Id = x.Key, 
          Quantity = x.Sum(y => x.Quantity
        });
like image 39
Femaref Avatar answered Sep 07 '25 08:09

Femaref