Generic Iterator

I just generalized the iterator implemented in my previous blog post to non-recursively iterate any object tree.

static IEnumerable<T> Iterate<T>(T rootNode, Func<T, IEnumerable<T>> getChildren)  
{
    var stack = new Stack<T>();
    stack.Push(rootNode);
    while (stack.Count > 0)
    {
        T node = stack.Pop();
        yield return node;
        IEnumerable<T> childNodes = getChildren(node);
        foreach (var childNode in childNodes)
            stack.Push(childNode);
    }
}
Google
m@kli.dk @klinkby RSS feed  GitHub