How to flatten tree via LINQ?

后端 未结 14 2207
抹茶落季
抹茶落季 2020-11-22 04:56

So I have simple tree:

class MyNode
{
 public MyNode Parent;
 public IEnumerable Elements;
 int group = 1;
}

I have a I

14条回答
  •  鱼传尺愫
    2020-11-22 05:47

    Just for completeness, here is the combination of the answers from dasblinkenlight and Eric Lippert. Unit tested and everything. :-)

     public static IEnumerable Flatten(
            this IEnumerable items,
            Func> getChildren)
     {
         var stack = new Stack();
         foreach(var item in items)
             stack.Push(item);
    
         while(stack.Count > 0)
         {
             var current = stack.Pop();
             yield return current;
    
             var children = getChildren(current);
             if (children == null) continue;
    
             foreach (var child in children) 
                stack.Push(child);
         }
     }
    

提交回复
热议问题