Search code examples
c#.nettraversalobject-graph

C# .Net Traversing an object graph


I have found this method written by Eric Lippert to traverse an object graph:

static IEnumerable<T> Traversal<T>(T item, Func<T, IEnumerable<T>> children)
{
    var seen = new HashSet<T>();
    var stack = new Stack<T>();
    seen.Add(item);
    stack.Push(item);
    yield return item;
    while (stack.Count > 0)
    {
        T current = stack.Pop();
        foreach (T newItem in children(current))
        {
            if (!seen.Contains(newItem))
            {
                seen.Add(newItem);
                stack.Push(newItem);
                yield return newItem;
            }
        }
    }
}

Does anyone have an example of how to use this?


Solution

  • Assuming a Console app, and a directory tree rooted at "C:\TEST", you can do this:

    string root = "C:\\Test";
    var folders = Traversal(root, Directory.EnumerateDirectories);
    
    foreach (var folder in folders)
        Console.WriteLine(folder);
    

    You could also try string root = "C:\\Program Files (x86)"; but you might get access exceptions with that.