搜索使用LINQ树 [英] Searching a tree using LINQ
本文介绍了搜索使用LINQ树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从这个类创建的树。
class Node
{
public string Key { get; }
public List<Node> Children { get; }
}
我希望所有的孩子和他们的孩子进行搜索以获取那些符合一个条件:
I want to search in all children and all their children to get the ones matching a condition:
node.Key == SomeSpecialKey
我怎样才能实现呢?
How can I implement it?
推荐答案
这是一种误解,这需要递归。它的将会的要求堆栈或队列,最简单的方法是使用递归来实现它。对于为了完整起见,我将提供一个非递归的答案。
It's a misconception that this requires recursion. It will require a stack or a queue and the easiest way is to implement it using recursion. For sake of completeness I'll provide a non-recursive answer.
static IEnumerable<Node> Descendants(this Node root)
{
var nodes = new Stack<Node>(new[] {root});
while (nodes.Any())
{
Node node = nodes.Pop();
yield return node;
foreach (var n in node.Children) nodes.Push(n);
}
}
使用这种EX pression例如使用它:
Use this expression for example to use it:
root.Descendants().Where(node => node.Key == SomeSpecialKey)
这篇关于搜索使用LINQ树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文