tags:

views:

1961

answers:

2

I have two classes:

class Foo 
{ 
    public Bar SomeBar { get; set; } 
}

class Bar
{ 
    public string Name { get; set; } 
}

I have a list of Foos that I group together:

var someGroup = from f in fooList
                orderby f.SomeBar.Name ascending
                group f by f.SomeBar.Name into Group
                select Group;

How can I get the list of the distinct Bars from someGroup?

+2  A: 

Will there potentially be more than one Bar with the same name? If so, it's tricky. If not, you could just change it to:

var grouped = from f in fooList
              orderby f.SomeBar.Name ascending
              group f by f.SomeBar into Group
              select Group;

var bars = grouped.Select(group => group.Key);

Alternatively, if you only want one Bar per name, you could stick with your original query, but change the last bit:

var someGroup = from f in fooList
                orderby f.SomeBar.Name ascending
                group f by f.SomeBar.Name into Group
                select Group;

var bars = someGroup.Select(group => group.First().SomeBar);

This will take the first Foo in each group, and find its Bar.

Jon Skeet
A: 

If you define "being distinct" by a special Equals implementation for Bar, you could use:

var result = someGroup.SelectMany(x => x.Select(t => t.SomeBar)).Distinct();
Mehrdad Afshari