LINQ to DataSet Group By Multiple Columns - Method Syntax

10,653

Solution 1

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

Solution 2

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));
Share:
10,653
FMFF
Author by

FMFF

Perpetual Newbie

Updated on June 04, 2022

Comments

  • FMFF
    FMFF almost 2 years

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