递归层次家长的孩子 [英] Recursive Hierarchical Parent child
问题描述
我有一个项目,从它有一个 PARENTID
值或空数据库未来的集合。
I have a collection of items coming from a database which has a parentid
value or null.
下面是我的课的设计:
public class Item
{
public int id{get;set;}
public string Name{get;set;}
public int? ParentId{get;set;}
public List<Item> SubItems{get;set;}
}
我想建立从集合项目的层次结构。假设一个集合是100个项目从中我需要根据的ParentId映射构建结构。
I want to build a hierarchical structure of Items from the collection. Assume a collection is 100 items from which I need to construct the structure based on the ParentId mapping.
我想这个帖子<一个href="http://www.superstar$c$crs.com/blogs/posts/recursive-hierarchical-joins-in-c-sharp-and-linq.aspx"相对=nofollow>递归分层加入C#和LINQ 但它给了我一个错误,如果的ParentId为null。
I tried this post Recursive Hierarchical Joins in C# and LINQ but it gives me an error if ParentId is null.
也试过<一个href="http://stackoverflow.com/questions/15867478/build-tree-type-list-by-recursively-checking-parent-child-relationship-c-sharp">Build通过递归检查父子关系的C#,但这种方法也并没有为我工作树型列表。
Also tried Build tree type list by recursively checking parent-child relationship C# , but this solution also does not work for me.
我如何做到这一点?
推荐答案
您可以使用此方法:
- 从数据库中获取的所有项目(不填充子项)。
- 构建
查找&LT; INT,项目&GT;
父ID和项目与父母的id - 遍历的项目和关联使用查找该子项的每个项目。
- Get all the items from the database (without filling the SubItems).
- Build a
Lookup<int?,Item>
of parent ids and items with that parent id. - Loop through the items and associate each item with the subitems using the lookup.
code:
var items = // get from the database... (e.g. as a list)
var lookup = items.ToLookup(x => x.ParentId);
foreach (var item in items)
item.SubItems = lookup[item.Id].ToList();
由于 @EamonNerbonne 下面的评论,你可以得到的根元素为好,如果你需要:
As @EamonNerbonne commented below, you can get the root elements as well, if you need to:
var roots = lookup[null].ToList();
这篇关于递归层次家长的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!