递归层次结构 - 使用 Linq 的递归查询 [英] Recursive Hierarchy - Recursive Query using Linq

查看:52
本文介绍了递归层次结构 - 使用 Linq 的递归查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架(版本 6)来映射到递归层次结构,并且映射得很好.

I am using Entity Framework (version 6) to map to a recursive hierarchy and it maps nicely.

我的问题是我想递归获取层次结构中特定节点的 ALL 子节点.

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?

推荐答案

虽然在这里可以使用递归方法,但您可以使用显式堆栈来遍历此树结构,以避免使用堆栈空间,这不是对于大型树结构总是足够的.这样的方法作为迭代器块也很不错,并且迭代器块在递归时比常规方法要便宜得多,因此它也会表现得更好:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆