在C#中以函数方式遍历树

Ben*_*ton 7 c# linq functional-programming

在c#,Traverse中考虑以下扩展方法:

IEnumerable<T> Traverse<T>( this IEnumerable<T> source, 
                              Func<T, IEnumerable<T>> fnRecurse );
Run Code Online (Sandbox Code Playgroud)

这种方法允许人们通过T定义的树来递归,并且任何函数都会导致T返回其子节点.

现在考虑以下T的实现:

class Node
{
  public string Name;
  public List<Node> Children;
}
Run Code Online (Sandbox Code Playgroud)

我的目标是编写可能的最短函数,它将返回包含此树中每个节点的完全限定路径的IEnumerable.就像是:

var node = GetParentNode();
return node.Traverse( node => node.Children )
           .Select( node => GetParentName(node) + ":" + node.Name );
Run Code Online (Sandbox Code Playgroud)

显然,向Node添加Parent属性会使问题变得微不足道.相反,我想以某种方式在仿函数中构建我的父字符串.我不认为这在C++中会太难,但我不知道如何在C#中做到这一点.有任何想法吗?

Jar*_*Par 9

我认为诀窍就是不要传递一种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);
Run Code Online (Sandbox Code Playgroud)