Let\'s suppose if we have a class like:
class Person {
internal int PersonID;
internal string car;
}
I have a list of this class
An alternative way to do this could be select distinct PersonId
and group join with persons
:
var result =
from id in persons.Select(x => x.PersonId).Distinct()
join p2 in persons on id equals p2.PersonId into gr // apply group join here
select new
{
PersonId = id,
Cars = gr.Select(x => x.Car).ToList(),
};
Or the same with fluent API syntax:
var result = persons.Select(x => x.PersonId).Distinct()
.GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
{
PersonId = id,
Cars = gr.Select(x => x.Car).ToList(),
});
GroupJoin produces a list of entries in the first list ( list of PersonId
in our case), each with a group of joined entries in the second list (list of persons
).