Reputation: 3173
My class:
public class Foo
{
public int A { get; set; }
public List<Bar> Bars { get; set; }
}
I've got IEnumerable<Foo>
. I would like get List<Foo>
grouping by A, and get Bars list, which contais all elements at Bars for group.
So final Foo.Bars should contains all elements of Bar at group
Is it possible with linq?
Upvotes: 2
Views: 1028
Reputation: 460288
var result = foos.GroupBy(f => f.A)
.SelectMany(grp => grp.Select(f => f.Bars));
As Rawling has mentioned, this returns not an IEnumerable<Foo>
, so try this:
IEnumerable<Foo> result =
foos.GroupBy(f => f.A)
.Select(grp => new Foo() {
A = grp.Key,
Bars = grp.SelectMany(ff => ff.Bars).Distinct().ToList()
});
I'm not sure whether you want a distinct list of Bars
or not. Note that you may need to override Equals
and GetHashCode
in class Bar
.
Upvotes: 5