Goran Goran - 1 month ago 9
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

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)  
    {  
        Console.WriteLine(Child.Name);  
    }  
    Console.WriteLine();  
}
Comments