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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With