递归层次结构 - 使用LINQ递归查询 [英] Recursive Hierarchy - Recursive Query using Linq
问题描述
我使用实体框架(第6版)映射到一个递归层次结构,它很好地映射。
I am using Entity Framework (version 6) to map to a recursive hierarchy and it maps nicely.
我的问题是,我想递归获得全部层次结构中的一个特定节点的子节点。
My issue is that I want to recursively get ALL Child Nodes of a particular node in the hierarchy.
我得到的子节点很容易地使用LINQ:
I get the child nodes quite easily using Linq:
var recursiveList = db.ProcessHierarchyItems
.Where(x => x.id == id)
.SelectMany(x => x.Children);
是否有人知道一个干净的实施,这将递归得到所有的孩子?
Does anybody know of a clean implementation, that will recursively get all children?
谢谢,
基思。
Thanks, Keith.
推荐答案
虽然可以在这里使用递归的方法,你可以使用一个明确的堆栈,而不是避免使用堆栈空间,这是不遍历这个树结构总是足够大的树结构。这种方法也是很不错的迭代器块,和迭代器块递归比普通方法便宜得多的时候,所以这将有更好的表现,以及:
While it is possible to use a recursive method here, you can traverse this tree structure using an explicit stack instead to avoid using the stack space, which isn't always sufficient for large tree structures. Such a method is also very nice as an iterator block, and iterator blocks are much less expensive when recursive than regular methods, so this will perform better as well:
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> items,
Func<T, IEnumerable<T>> childSelector)
{
var stack = new Stack<T>(items);
while(stack.Any())
{
var next = stack.Pop();
yield return next;
foreach(var child in childSelector(next))
stack.Push(child);
}
}
这篇关于递归层次结构 - 使用LINQ递归查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!