How to group the value of an IEnumerable property

Let's 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 Title

, so the result will be

 { {"Id": 0, "Title": "a"}, {"Id": 0, "Title": "b"}, {"Id": 0, "Title": "c"} };

      

Prefer LINQ solution. Tried to do:

var result = A.GroupBy(x => x.B)

      

(I expected this to not work) and

var result = A.SelectMany(x => x.B).GroupBy(x => x)

      

but then I only have titles. How can i do this?

+3


source to share


1 answer


You are not grouping, you are doing the opposite - antialiasing - this is done with SelectMany

:



A.SelectMany(a => a.B, (a, b) => new {a.Id, b.Title});

      

+7


source







All Articles