tags:

views:

168

answers:

3
    var expr = Data.Customers
        .GroupBy(c => c.Country, c => c.Name);

    foreach (IGrouping<Countries, string> customerGroup in expr)
    {                
        Trace.WriteLine("Country: " + customerGroup.Key);
        foreach (var item in customerGroup)
        {
            Trace.WriteLine(item);
        }
        Trace.WriteLine("");
    }

I wish I got following result:

Country: Italy

Paolo Marco

Country: USA

James Frank

instead of:

Country: Italy Paolo Marco

Country: USA James Frank Frank

If it is possible, please make it using standard LINQ syntax.

A: 

At first glance, I think you don't need to group by Name

var expr = Data.Customers
        .GroupBy(c => c.Country);
shahkalpesh
A also need to group the sequence by name
G2
+4  A: 

If you want to group by multiple keys you have to use an anonymous type:

var expr = Data.Customers 
             .GroupBy(c =>new{c.Country, c.Name}); 

Then you can access expr.Key.Country and expr.Key.Name.

Carles
A: 
    var expr = Data.Customers
                    .Select(c => new { c.Country, c.Name})
                    .Distinct()
                    .GroupBy(c => c.Country, c => c.Name);

I've found a clumsy solution, but without using LINQ syntax.

G2
I don't understand what you are trying to achieve. This query really makes no sense (or I don't see it). What is the purpose of grouping into groups of just one element?
Carles
I've already achieved the result. I hopped to filter the customers by their names using the GroupBy operator, because I didn't want to have several similar names like Frank and then I wanted to group the customers by their countries.
G2
I'd be pleased if somebody told me know how to achive the same result using LINQ syntax.
G2
I misread your answer and didn't understand your question... What's wrong with using this sintax vs the "standard Linq Syntax"?
Carles