使用 LINQ 搜索树 [英] Searching a tree using LINQ
本文介绍了使用 LINQ 搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从这个类创建了一棵树.
I have a tree created from this class.
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
我该如何实施?
推荐答案
认为这需要递归是一种误解.它将需要一个堆栈或一个队列,最简单的方法是使用递归来实现它.为了完整起见,我将提供一个非递归的答案.
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);
}
}
以这个表达式为例来使用它:
Use this expression for example to use it:
root.Descendants().Where(node => node.Key == SomeSpecialKey)
这篇关于使用 LINQ 搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文