Sublists with Group by

Question

Let's suppose if we have a class like
class Person { 
    internal int PersonID; 
    internal string car  ; 
}
Now I have a list of this class: List persons; Now this list can have instances multiple same PersonIDs, for ex.
persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 
Is there a way I can group by personID and get the list of all the cars he has? For ex. expected result would be
class Result { 
   int PersonID;
   List cars; 
}
Could someone please point me in the right direction?

Answer

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 view as an IEnumerable) is a sequence of whatever values were in the projection (p.car in this case) present for the given key Source

No comments:

HOWTO: Repair Logitech M325 Mouse

FixIt says that you will find single screw under CE label. It isn't always true.