考虑 C# 中的以下扩展方法 Traverse:
IEnumerable<T> Traverse<T>( this IEnumerable<T> source,
Func<T, IEnumerable<T>> fnRecurse );
此方法允许人们递归遍历由 T 定义的树以及导致 T 返回其子节点的任何函数。
现在考虑 T 的以下实现:
class Node
{
public string Name;
public List<Node> Children;
}
我的目标是编写尽可能短的函数来返回 IEnumerable
包含此树中每个节点的完全限定路径。就像是:
var node = GetParentNode();
return node.Traverse( node => node.Children )
.Select( node => GetParentName(node) + ":" + node.Name );
显然,向 Node 添加 Parent 属性使问题变得微不足道。相反,我想以某种方式在函子内构建我的父字符串。我不认为这在 C++ 中太难,但我不知道如何在 C# 中做到这一点。有任何想法吗?
我认为诀窍就是不传递Node
类型。而是传递下来Node
这是合格的路径。例如
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)