Group by in LINQ

后端 未结 10 1600
悲哀的现实
悲哀的现实 2020-11-21 06:58

Let\'s suppose if we have a class like:

class Person { 
    internal int PersonID; 
    internal string car; 
}

I have a list of this class

10条回答
  •  隐瞒了意图╮
    2020-11-21 07:36

    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).

提交回复
热议问题