2

I have a DataTable that queries out something like below

usergroupid...userid......username
1.............1...........John
1.............2...........Lisa
2.............3...........Nathan
3.............4...........Tim

What I'm trying to do is write a LINQ statement that will return an array of UserGroup instances. The UserGroup class has properties of UserGroupId and Users. Users is an array of User instances. The User class then has properties of UserId and UserName.

Can filling such a hierarchy be done with a single LINQ statement and what would it look like?

Thanks a million

Fung
  • 7,530
  • 7
  • 53
  • 68

2 Answers2

5

Check this out, hope this helps

var users = new[] 
{
    new {UserGroupId = 1, UserId = 1, UserName = "John"},
    new {UserGroupId = 1, UserId = 2, UserName = "Lisa"},
    new {UserGroupId = 2, UserId = 3, UserName = "Nathan"},
    new {UserGroupId = 3, UserId = 4, UserName = "Tim"}
};

var userGroups = from user in users 
                 group user by user.UserGroupId into userGroup 
                 select new {
                                UserGroupId = userGroup.Key, 
                                Users = userGroup.ToList()
                            };

foreach (var group in userGroups)
{
    Console.WriteLine("{0} - {1}",group.UserGroupId, group.Users.Count);
}
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
Rohan West
  • 9,262
  • 3
  • 37
  • 64
-2

There is - look at GroupBy and Select methods.

Ana Betts
  • 73,868
  • 16
  • 141
  • 209