Let\'s suppose if we have a class like:
class Person {
internal int PersonID;
internal string car;
}
I have a list of this class
I have created a working code sample with Query Syntax and Method Syntax. I hope it helps the others :)
You can also run the code on .Net Fiddle here:
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public int PersonId;
public string car ;
}
class Result
{
public int PersonId;
public List Cars;
}
public class Program
{
public static void Main()
{
List persons = new List()
{
new Person { PersonId = 1, car = "Ferrari" },
new Person { PersonId = 1, car = "BMW" },
new Person { PersonId = 2, car = "Audi"}
};
//With Query Syntax
List results1 = (
from p in persons
group p by p.PersonId into g
select new Result()
{
PersonId = g.Key,
Cars = g.Select(c => c.car).ToList()
}
).ToList();
foreach (Result item in results1)
{
Console.WriteLine(item.PersonId);
foreach(string car in item.Cars)
{
Console.WriteLine(car);
}
}
Console.WriteLine("-----------");
//Method Syntax
List results2 = persons
.GroupBy(p => p.PersonId,
(k, c) => new Result()
{
PersonId = k,
Cars = c.Select(cs => cs.car).ToList()
}
).ToList();
foreach (Result item in results2)
{
Console.WriteLine(item.PersonId);
foreach(string car in item.Cars)
{
Console.WriteLine(car);
}
}
}
}
Here is the result:
1 Ferrari BMW 2 Audi ----------- 1 Ferrari BMW 2 Audi