Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq objects grouping

I have people object and poeple have property group that make them belong to different groups. I want to get List and put it in an object GrouppedPeople, in which there would be List coll. One coll element contain only people that belong to same group.

So if I had 3 people:

List<People>(){new People{Name="Test", Group = "Group1"},
               new People{Name="SameGroup", Group = "Group1"},
               new People{Name="Other", Group = "OtherGroup"}}

I need to have a collection of 2 GrouppedPeople. First will contain Test and SameGroup, and second will contain Other (groupped by Group property). Im trying to do this using linq.

I need results to be of type List. GrouppedPeople is a class that have only one property of type List and all poeple are from the same group.

Ive came out with something like this:

from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select g;

Its working fine, but the result object is not strongly typed. And Id like to have List as the result. Is there a way to get it from that anonymous object type? Any other ways to get this all with linq and keep strong typing?

like image 410
Yaroslav Yakovlev Avatar asked Jan 20 '23 19:01

Yaroslav Yakovlev


1 Answers

This will return List of anonymous type objects:

var result = (from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select g).ToList();

But if you want to return specific type objects you should create new class with required properties:

public class MateGroup
{
 public string Name {get;set;}
}

var result = (from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select new MateGroup(){ Name =  g.<field_name>}).ToList();

UPD:

According to your comment please try the following:

var result = (from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select new GrouppedPeople(){ People =  g.ToList()}).ToList();
like image 65
Pavel Morshenyuk Avatar answered Jan 28 '23 07:01

Pavel Morshenyuk