Group by in LINQ
Asked 07 September, 2021
Viewed 2K times
  • 57
Votes

Let's suppose if we have a class like:

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

I have a list of this class: List<Person> persons;

And this list can have multiple instances with same PersonIDs, for example:

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 example, the expected result would be

class Result { 
   int PersonID;
   List<string> cars; 
}

So after grouping, I would get:

results[0].PersonID = 1; 
List<string> cars = results[0].cars; 

result[1].PersonID = 2; 
List<string> cars = result[1].cars;

From what I have done so far:

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, // this is where I am not sure what to do

Could someone please point me in the right direction?

10 Answer