C # Select Distinguishing Values โ€‹โ€‹from IGrouping

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 a list of individual bars from a certain group?

+3
source share
3 answers

Will there be potentially more than one bar with the same name? If so, it is difficult. If not, you can simply 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 want only one panel for the name, you can stick to the original request, 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);

It will take the first Foo in each group and find it Bar.

+7
source

If you define an โ€œexcellentโ€ special implementation Equalsfor Bar, you can use:

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

, :

var newlist<T2> = oldlist<T1>.GroupBy(g => g.distinct_var).Select(g => g.First()) //a
                 .Select(r=> new T2() {var1=r.va1, var2=r.var2 ...etc}).ToList(); //b

:

. , .

. 1 2, T2.

, , , .

0
source

Source: https://habr.com/ru/post/1703903/


All Articles