tags:

views:

637

answers:

1

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() });
+5  A: 

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 Once again, beaten by the Skeet...
Dave Swersky
Jon,I am always commiting mistake on using extension method ,is there any easy way to be familiar with?
Udana
@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