首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用LINQ搜索树

使用LINQ搜索树
EN

Stack Overflow用户
提问于 2011-08-15 16:19:21
回答 11查看 43.7K关注 0票数 90

我有一个从这个类创建的树。

代码语言:javascript
复制
class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}

我想搜索所有的孩子及其所有的孩子,以获得符合条件的孩子:

代码语言:javascript
复制
node.Key == SomeSpecialKey

我如何实现它?

EN

回答 11

Stack Overflow用户

发布于 2011-08-15 16:29:12

Searching a Tree of Objects with Linq

代码语言:javascript
复制
public static class TreeToEnumerableEx
{
    public static IEnumerable<T> AsDepthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> childrenFunc)
    {
        yield return head;

        foreach (var node in childrenFunc(head))
        {
            foreach (var child in AsDepthFirstEnumerable(node, childrenFunc))
            {
                yield return child;
            }
        }

    }

    public static IEnumerable<T> AsBreadthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> childrenFunc)
    {
        yield return head;

        var last = head;
        foreach (var node in AsBreadthFirstEnumerable(head, childrenFunc))
        {
            foreach (var child in childrenFunc(node))
            {
                yield return child;
                last = child;
            }
            if (last.Equals(node)) yield break;
        }

    }
}
票数 16
EN

Stack Overflow用户

发布于 2011-08-15 16:35:27

如果你想保持类似Linq的语法,你可以使用一个方法来获得所有的子代(子代+子代等)。

代码语言:javascript
复制
static class NodeExtensions
{
    public static IEnumerable<Node> Descendants(this Node node)
    {
        return node.Children.Concat(node.Children.SelectMany(n => n.Descendants()));
    }
}

然后,可以像查询任何其他可枚举对象一样,使用where或first或任何其他方法来查询此可枚举对象。

票数 16
EN

Stack Overflow用户

发布于 2011-08-15 16:28:39

您可以尝试此扩展方法来枚举树节点:

代码语言:javascript
复制
static IEnumerable<Node> GetTreeNodes(this Node rootNode)
{
    yield return rootNode;
    foreach (var childNode in rootNode.Children)
    {
        foreach (var child in childNode.GetTreeNodes())
            yield return child;
    }
}

然后将其与Where()子句一起使用:

代码语言:javascript
复制
var matchingNodes = rootNode.GetTreeNodes().Where(x => x.Key == SomeSpecialKey);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7062882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档