LINQ to DataSet Group By Multiple Columns - Method Syntax

10.7k views Asked by At

My question is identical to two previously asked questions

LINQ TO DataSet: Multiple group by on a data table, the only difference with this question is that I need to do that with Method Syntax.
and

LINQ Group By Multiple fields -Syntax help - the difference with this question is that I need to do this using LINQ-to-DataSet.

I'm trying to group the Customers by Country, with the result (expected) as below:

   COUNTRYCODE     CUSTOMERNAME
   USA             Microsoft   
   USA             IBM
   CAN             RIM
   CAN             Tim Horton
   GER             BMW

How do we do this? Thank you.

EDIT:

Here's the messy code I'm struggling with.

   var query = orders.AsEnumerable()
                    .GroupBy(t => new {CountryCode= t.Field<string>("CountryCode"), 
                                       CustomerName = t.Field<string>("CustomerName"), 
                                    (key, group)=> new {Key1 = key.CountryCode, Key2=key.CustomerName})
                    .Select(t => new {t.Key1, t.Key2});
2

There are 2 answers

0
FMFF On BEST ANSWER

The code in my EDIT worked:

 var query = orders.AsEnumerable()   
              .GroupBy(t => new {CountryCode= t.Field<string>("CountryCode"),
                                 CustomerName=t.Field<string>("CustomerName"),
                           (key, group)=> new {CountryCode = key.CountryCode,CustomerName=key.CustomerName})
.Select(t => new {t.CountryCode, t.CustomerName}); 
2
Tim Schmelter On
var uniqueCountryCustomer =
         tblCustomer.AsEnumerable()
        .GroupBy(row => new
        {
            Country = (string)row["COUNTRYCODE"],
            Customer = (string)row["CUSTOMERNAME"]
        });

For the sake of completeness, here is the query-syntax:

var uniqueCountryCustomer = 
            from row in tblCustomer.AsEnumerable()
            group row by new{
                Country=(string)row["COUNTRYCODE"],
                Customer=(string)row["CUSTOMERNAME"]
            };

// display result
var summary = from cc in uniqueCountryCustomer
              select string.Format("Country:{0} Customer:{1} Count:{2}", 
              cc.Key.Country, 
              cc.Key.Customer, 
              cc.Count());
MessageBox.Show(string.Join(Environment.NewLine,summary));