How to flatten tree via LINQ?

后端 未结 14 2193
抹茶落季
抹茶落季 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:50

    In case anyone else finds this, but also needs to know the level after they've flattened the tree, this expands on Konamiman's combination of dasblinkenlight and Eric Lippert's solutions:

        public static IEnumerable> FlattenWithLevel(
                this IEnumerable items,
                Func> getChilds)
        {
            var stack = new Stack>();
            foreach (var item in items)
                stack.Push(new Tuple(item, 1));
    
            while (stack.Count > 0)
            {
                var current = stack.Pop();
                yield return current;
                foreach (var child in getChilds(current.Item1))
                    stack.Push(new Tuple(child, current.Item2 + 1));
            }
        }
    

提交回复
热议问题