So I have simple tree:
class MyNode
{
public MyNode Parent;
public IEnumerable Elements;
int group = 1;
}
I have a I
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));
}
}