简体   繁体   English

如何使用父子关系初始化列表

[英]How to initialize list with parent child relation

Let's say I have the following classes: 假设我有以下课程:

public class Parent
{
   public string name;
   IList<Child> 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? 从数据库中获取所有的父母和所有的孩子然后使用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? 还是获取所有父母,并遍历每个父母以使用parentName查询数据库以获取孩子信息? Due to requirement that I have, I cannot use datatable or dataset; 由于我的要求,我无法使用数据表或数据集; I can only use datareader. 我只能使用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 谢谢

If you are not able to leverage LinqToSql, Entity Framework or some other custom querying method and you must load all the parents and their children in the database per the manor you suggest then your first option is most likely superior. 如果您无法利用LinqToSql,Entity Framework或其他自定义查询方法,并且必须按照您建议的方式将所有父级及其子级加载到数据库中,那么您的第一个选择很可能会更好。 Assuming you'll query all the rows of both tables, the first option will result in only two database queries. 假设您将查询两个表的所有行,则第一个选项将仅导致两个数据库查询。 In the second option you'll have as many queries as there are children plus the query for the parents. 在第二个选项中,您将拥有与子项以及父项查询一样多的查询。

EDIT 编辑

Additionally, especially if the data sets are large you can achieve further performance by using Enumerable.ToLookup . 此外,尤其是如果数据集很大,则可以使用Enumerable.ToLookup获得更高的性能。 This essentially creates a sorted dictionary for you which makes searching for the appropriate children much more efficient as the framework can make use of a binary search. 从本质上讲,这为您创建了一个排序的字典,这使搜索适当的子代更加高效,因为框架可以使用二进制搜索。 You could use it as follows: 您可以按以下方式使用它:

var children = GetChildren().ToLookup(p => p.parentName);

... and then in your loop ... ...然后在您的循环中...

parent.children = children[parent.name].ToList();

我认为,如果父级和子级具有基本字段,则数据库中应该为它们提供一个表,并具有一个附加属性Parent ,它引用同一表row,(因此它指向数据库中的父级),您可以确定,如果该行是子级或父级,如果其Parent不为null,则它应该是具有Parent的行的子元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM