Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq projection of flattened table into parent and child object graph

Tags:

c#

linq

I have a enumerable list that contains a flattened parent-child relationship:

ParentGuid1, ParentName1, ChildGuid1, ChildName1
ParentGuid1, ParentName1, ChildGuid2, ChildName2
ParentGuid2, ParentName2, ChildGuid3, ChildName3
ParentGuid2, ParentName2, ChildGuid4, ChildName4

I have defined a Child class and a Parent class that includes a List<Child> property called Children.

Can I use linq to create on object graph with one instance of the Parent class per unique ParentGuid, referencing a List populated by the children associated with that parent.

Something along the lines of this (note, this code doesn't compile):

myFlattenedHierarchy.Select(p => new Parent
   {Guid = p.ParentGuid, 
    Name = p.ParentName, 
    Children = myFlattenedHierarchy.Where(c => c.ParentGuid == p.ParentGuid).Select(c => new Child{Guid = c.ChildGuid, Name = c.ChildName})
   });
like image 330
Adam Flynn Avatar asked Sep 29 '11 13:09

Adam Flynn


1 Answers

myFlattenedHierarchy.Select(p => new Parent
   {Guid = p.ParentGuid, 
    Name = p.ParentName, 
    Children = myFlattenedHierarchy.Where(c => c.ParentGuid == p.ParentGuid).Select(c => new Child{Guid = c.ChildGuid, Name = c.ChildName})
   });

You should be able to do that, but the Children can not be a List, it has to be IEnumerable.

like image 152
AD.Net Avatar answered Sep 29 '22 10:09

AD.Net