How to group by Properties and select other properties as lists using LINQ?
I'm bad at explaining it so here's an example:
Lets say I have a list of C# objects that can be represented in JSON like this:
[
{ "id":123, "name":"John", "carId":1, "carAge":3 },
{ "id":123, "name":"John", "carId":2, "carAge":4 },
{ "id":4, "name":"Mary", "carId":3, "carAge":3 },
{ "id":4, "name":"Mary", "carId":4, "carAge":3 },
{ "id":123, "name":"John", "carId":5, "carAge":3 }
]
Among all those objects only carId
is unique.
I would like to group them by person details and join those details with connected car details.
The end result would look like this but as c# objects:
[
{"id":123, "name":"John",
[
{"carId":1, "carAge":3},
{"carId":2, "carAge":4},
{"carId":5, "carAge":3}
]
},
{"id":4, "name":"Mary",
[
{"carId":3, "carAge":3},
{"carId":4, "carAge":3}
]
}
]
Edit:
I'm stuck after
list.GroupBy(x => new { x.Id, x.Name })
because I don't need any aggregate functions but only selection.
I apologize for not posting more code, this is a simplified version, the real thing has more filtering and convoluted domain specific terminology.
Everything is done in memory - without DB to worry about.