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})
});
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
.
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