我有一个从这个类创建的树。
class Node
{
public string Key { get; }
public List<Node> Children { get; }
}
我想搜索所有的孩子及其所有的孩子,以获得符合条件的孩子:
node.Key == SomeSpecialKey
我如何实现它?
发布于 2011-08-15 16:29:12
Searching a Tree of Objects with Linq
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;
}
}
}
发布于 2011-08-15 16:35:27
如果你想保持类似Linq的语法,你可以使用一个方法来获得所有的子代(子代+子代等)。
static class NodeExtensions
{
public static IEnumerable<Node> Descendants(this Node node)
{
return node.Children.Concat(node.Children.SelectMany(n => n.Descendants()));
}
}
然后,可以像查询任何其他可枚举对象一样,使用where或first或任何其他方法来查询此可枚举对象。
发布于 2011-08-15 16:28:39
您可以尝试此扩展方法来枚举树节点:
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()
子句一起使用:
var matchingNodes = rootNode.GetTreeNodes().Where(x => x.Key == SomeSpecialKey);
https://stackoverflow.com/questions/7062882
复制相似问题