How to initialize list with parent child relation

Posted by user2917702 on Stack Overflow See other posts from Stack Overflow or by user2917702
Published on 2013-10-24T21:50:36Z Indexed on 2013/10/24 21:54 UTC
Read the original article Hit count: 130

Filed under:
|
|
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ