穿越功能在C#中的树 [英] Functionally traversing a tree in C#
问题描述
考虑下面的扩展方法在C#中,遍历:
Consider the following extension method in c#, Traverse:
IEnumerable<T> Traverse<T>( this IEnumerable<T> source,
Func<T, IEnumerable<T>> fnRecurse );
这个方法允许通过一棵树一个递归被T的定义和任何功能使T可返回其。子节点
This method allows one to recurse through a tree as defined by T and whatever function causes T to return its subnodes.
现在考虑以下实现的T:
Now consider the following implementation of T:
class Node
{
public string Name;
public List<Node> Children;
}
我的目标是编写最短的功能可能会返回一个IEnumerable $ B包含在这棵树的每个节点的完全合格的路径$ b。是这样的:
My goal is to write the shortest function possible that will return an IEnumerable containing the fully qualified paths for every node in this tree. Something like:
var node = GetParentNode();
return node.Traverse( node => node.Children )
.Select( node => GetParentName(node) + ":" + node.Name );
显然,加入Parent属性节点使问题微不足道。相反,我想建立一个仿里面我父母不知何故字符串。我不认为这会在C太难+ +,但我看不出如何做到这一点在C#。任何想法?
Obviously, adding a Parent property to Node makes the problem trivial. Instead I'd like to build my parent strings inside a functor somehow. I don't think this would be too hard in C++ but I don't see how to do it in C#. Any ideas?
推荐答案
我认为,关键是要根本无法通过倒节点
类型。相反,通过按下节点
,它是合格的路径。例如:
I think the trick is to simply not pass down a Node
type. Instead pass down the Node
and it's qualified path. For example
var node = GetTheStartNode();
var start = new { Path = node.Name; Node = node };
var paths =
start
.Traverse( x => x.Node.Children.Select(
c => new { .Path = x.Path + ":" c.Name; .Node=c) )
.Select(x => x.Path);
这篇关于穿越功能在C#中的树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!