Group by in LINQ

后端 未结 10 1622
悲哀的现实
悲哀的现实 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:21

    Absolutely - you basically want:

    var results = from p in persons
                  group p.car by p.PersonId into g
                  select new { PersonId = g.Key, Cars = g.ToList() };
    

    Or as a non-query expression:

    var results = persons.GroupBy(
        p => p.PersonId, 
        p => p.car,
        (key, g) => new { PersonId = key, Cars = g.ToList() });
    

    Basically the contents of the group (when viewed as an IEnumerable) is a sequence of whatever values were in the projection (p.car in this case) present for the given key.

    For more on how GroupBy works, see my Edulinq post on the topic.

    (I've renamed PersonID to PersonId in the above, to follow .NET naming conventions.)

    Alternatively, you could use a Lookup:

    var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);
    

    You can then get the cars for each person very easily:

    // This will be an empty sequence for any personId not in the lookup
    var carsForPerson = carsByPersonId[personId];
    

提交回复
热议问题