Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Select Distinct Values from IGrouping

Tags:

c#

lambda

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?

like image 356
blu Avatar asked Dec 14 '25 19:12

blu


1 Answers

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.

like image 186
Jon Skeet Avatar answered Dec 16 '25 12:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!