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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With