Goran Goran - 1 year ago 65
C# Question

Create a parent -> children hierarchy from two collections

I have two separate collections instances filled with data

List<Parent> parents;
List<Child> children;

two collections can be connected through Child.ParentId, and Parent.Children.

parents collection does not have Children property populated, so how can I link Parent objects with Children?

Answer Source

Try this:

var result = from d in parents  
             join s in children  
             on d.ParentID equals s.ParentID into g  
             select new  
                 ParentName = d.ParentName,  
                 ChildList = g  

foreach (var item in result)  
    Console.WriteLine("Parent: {0}", item.ParentName);  
    foreach (var Child in item.ChildList)  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download