I prefer the common C # syntax for writing LINQ queries, the clearer the simple request form.
You can use the result selector to resolve the grouping result as a typed object.
var resultList = mates .GroupBy(p => p.Group, (g, p) => new B() { Group = g, People = p.ToList() }) .ToList();
Full application code for the test console:
class People { public string Name; public string Group; } class GroupedPeople { public string Group; public List<People> People; } class Program { static void Main(string[] args) { var mates = new List<People>() { new People{Name="Test", Group = "Group1"}, new People{Name="SameGroup", Group = "Group1"}, new People{Name="Other", Group = "OtherGroup"} }; var resultList = mates .GroupBy(p => p.Group, (g, p) => new GroupedPeople() { Group = g, People = p.ToList() }) .ToList(); } }
To call GroupBy, two arguments are required:
p => p.Group - this lambda (anonymous method) used to return the grouping key
(g, p) => new GroupedPeople() { Group = g, People = p.ToList() }
This lambda, used to create a GroupedPeople object based on the group parameters, the first argument is the grouping key, which is selected by the first lambda, the second argument is an enumeration with elements related to the current group.
source share