Reputation: 3809
Lets say I have
class Class1 A {
int Id;
IEnumerable<Class2> B;
}
class Class2 B {
string Title;
}
So if I have (in json format)
{Id: 0, B: [{"Title": "a"}, {"Title": "b"}, {"Title": "c"} ]}
I want to group by Title
so the result would be
{ {"Id": 0, "Title": "a"}, {"Id": 0, "Title": "b"}, {"Id": 0, "Title": "c"} };
Prefer a solution with LINQ. Tried to do:
var result = A.GroupBy(x => x.B)
(I expected that this will not work) and
var result = A.SelectMany(x => x.B).GroupBy(x => x)
but then I have only titles. How I can do that?
Upvotes: 3
Views: 283
Reputation: 152501
You're not grouping, you're doing the opposite - flattening - which is done with SelectMany
:
A.SelectMany(a => a.B, (a, b) => new {a.Id, b.Title});
Upvotes: 7