我从这个类创建的树。
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)