Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Group By Multiple fields -Syntax help

Tags:

c#

linq

group-by

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() });
like image 639
Udana Avatar asked Dec 08 '09 18:12

Udana


1 Answers

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.)

like image 182
Jon Skeet Avatar answered Nov 05 '22 04:11

Jon Skeet