03-10-2024, 08:39 PM
I'm facing a bit of a problem with the LINQ GroupBy method in C#. I am trying to combine a list of cars owned by people, where each person is represented multiple times in a list, with each instance having potentially a different car. What I want to achieve is a consolidated result where I get a list of people, where each person has a list of all the cars they own. To illustrate, I have a Person class, and a list that contains multiple instances with the same PersonID but different cars.
Here is how my Person class looks:
And here's an example list:
I want to end up with a result in this format:
The part where I'm stuck is after grouping by PersonID, I'm not entirely sure how to select and construct the list of cars for each person. Here's what I've tried so far:
Any help on how to continue from here would be greatly appreciated.
Here is how my Person class looks:
Code:
}
And here's an example list:
Code:
},
new Person {
PersonID = 1, car = "BMW"
},
new Person {
PersonID = 2, car = "Audi"
}
};
I want to end up with a result in this format:
Code:
}
The part where I'm stuck is after grouping by PersonID, I'm not entirely sure how to select and construct the list of cars for each person. Here's what I've tried so far:
Code:
select new {
PersonID = g.Key, // What do I put here?
Any help on how to continue from here would be greatly appreciated.