-2

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?

Alexandre
  • 498
  • 2
  • 12
Daniel Billingham
  • 1,391
  • 5
  • 15
  • 25
  • 1
    What do you mean how to use it? Do you have particular task you are trying to solve? – Andrey Nov 14 '13 at 14:56
  • I mean I want an example of it in use? – Daniel Billingham Nov 14 '13 at 14:58
  • Do you need an explanation of the code? – Saeed Neamati Nov 14 '13 at 15:00
  • Look at the exact blog entry in which he provides that code. That's an example of it's use. Voila. – Servy Nov 14 '13 at 15:02
  • @servy Maybe he got the code from [here](http://stackoverflow.com/a/2209155/106159), which doesn't have a compilable example. I tried to search for the blog entry, and couldn't easily find it. – Matthew Watson Nov 14 '13 at 15:13
  • 1
    @MatthewWatson That post gives the exact date of the blog entry; given the date it's not too hard to find. http://blogs.msdn.com/b/ericlippert/archive/2010/02/08/making-the-code-read-like-the-spec.aspx – Servy Nov 14 '13 at 15:18

1 Answers1

4

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.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • The issue here is that the file system provides its own methods for traversing the file structure that's better than this method. It will perform better, won't have the same permissions issues, etc. – Servy Nov 14 '13 at 15:03
  • 2
    @Servy The point here is only to demonstrate the use of the Traversal method. We don't care if this is an efficient way to recursively descend a tree! – Matthew Watson Nov 14 '13 at 15:09