简体   繁体   中英

LINQ to DataSet Group By Multiple Columns - Method Syntax

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});
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));

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}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM