How to initialize list with parent child relation
- by user2917702
Let's say I have the following classes.
public class Parent
{
public string name;
IList<Children> children;
}
public class Child
{
public string parentName;
public int age;
}
As it is understandable, each parent can have multiple children, and we can have multiple parents. What is the best way to initialize these classes? Is it better to get all of the parents, and all of the children from database then use LINQ?
IList<Parent> parents = GetParents()//assume this gets parents from db
IList<Child> children = GetChildren() //assume this gets children from db
foreach(Parent parent in parents)
{
parent.children = children.Where(x=>x.parentName==parent.name).ToList();
}
or get all of the parents and iterate through each parent to query database by parentName to get children information? Due to requirement that I have, I cannot use datatable or dataset; I can only use datareader.
IList<Parent> parents = GetParents()//assume this gets parents from db
foreach(Parent parent in parents)
{
parent.children = GetChildrenByParentName();//assume this gets parents from db by parentName
}
Thank you