76

What is the correction needed for example 2 inorder to group by multiple columns

Example 1

var query = from cm in cust
            group cm by new { cm.Customer, cm.OrderDate } into cms
            select
            new 
            { Key1 = cms.Key.Customer,Key2=cms.Key.OrderDate,Count=cms.Count() };

Example 2 (incorrect)

   var qry = 
   cust.GroupBy(p => p.Customer, q => q.OrderDate, (k1, k2, group) =>
   new { Key1 = k1, Key2 = k2, Count = group.Count() });
Udana
  • 815
  • 1
  • 8
  • 6

1 Answers1

139

Use the same anonymous type in the dot notation that you do in the query expression:

var qry = cust.GroupBy(cm => new { cm.Customer, cm.OrderDate }, 
             (key, group) => new { Key1 = key.Customer, Key2 = key.OrderDate, 
                                   Count = group.Count() });

(In a real IDE I'd have (key, group) lined up under the cm parameter, but then it would wrap in SO.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Jon,I am always commiting mistake on using extension method ,is there any easy way to be familiar with? – Udana Dec 08 '09 at 18:48
  • @Udana: I've found it very helpful to look at what the C# compiler does with query expressions - but I'm a spec-based guy. Looking at the overloads available and reading the documentation also helps a lot :) – Jon Skeet Dec 08 '09 at 19:15
  • @Jon Skeet: This overload of `GroupBy()` does not have much of a description in MSDN. Can you please write a line about it? – FMFF Jan 27 '12 at 20:44
  • 4
    @FMFF: (https://msmvps.com/blogs/jon_skeet/archive/2011/01/01/reimplementing-linq-to-objects-part-21-groupby.aspx) As far as I can tell, this overload `groupBy(x=>x.y, (key,group)=>[lambda with group and key])` is just a shorter way to express `GroupBy(x=>x.y).select(group=>[lambda with group and group.key])`, and the second one seems more readable – HugoRune Apr 03 '12 at 20:01
  • 4
    i find that using linqpad also teaches a few things, since you can switch between: lambda and SQL after you write something in linq "from foo in bar select foo" syntax – Jim Wolff May 23 '12 at 11:58