0

So let's say i have a this class T which contains a List variable. How can I go through all items inside of List and then all items inside of each items of the List and so on until every single items have been treated? I know how to do this using a recursive method but i'm wondering if there is a way without using a recursive method that calls itself. Sorry if the question is confusing, a better example using folders could be as

Folder1 > contains Folder2, Folder3, Folder4

Folder2 > contains Folder5, Folder6

Folder5 > contains Folder7

Folder3 > contains Folder8, Folder9

Folder9 > contains Folder10

  Folder10 > contains Folder11

I would like to iterate through all of these folders in order (f1, f2, f5, f7, f6, f3, f8, f9, f10, f11, f4)

Does this make more sense? Thanks.

4

4 回答 4

2

This should do the job:

Stack stack;
stack.Push(root folder);
while (stack.Count > 0)
{
    Folder f = stack.Pop();
    foreach (Folder subf in f in reverse order)
        stack.Push(subf);
}
于 2013-03-30T16:36:36.337 回答
1
static IEnumerable<T> RecursiveEnumerator<T>( IEnumerable root ) {
     if (root is T) yield return (T)root;
     foreach (var item in root) {
         if (item is IEnumerable) {
             foreach (var result in RecursiveEnumerator<T>( (IEnumerable)item )) {
                 yield return result;
             }
         } else {
              if (item is T) yield return (T)item;
         }
     }
     yield break;
 }

 static IEnumerable<T> NonRecursiveEnumerator<T>( T root ) {
     Stack<T> Stack = new Stack<T>( );
     Stack.Push( root );

     do {
         root = Stack.Pop( );
         if (root is T) yield return (T)root;          
         if (root is IEnumerable)
            foreach (var item in ((IEnumerable<T>) root).Reverse()) 
               Stack.Push(item);
     } while (Stack.Count > 0);
     yield break;
  }

T shoud be an interface similar to this:

interface IStorageElement {
    string Name {get}
}
于 2013-03-30T15:00:34.123 回答
1

If the order you mentioned is important and must be exactly followed, your problem would be a Depth First Search over a simple tree. It a famous algorithm and you can find out how to solve it but the algorithm with a good performance is an iterative algorithm.

于 2013-03-30T15:37:00.580 回答
0

I would recommend the use of the foreach. For example

foreach(List node in T)
    foreach(List folders in node)
        //do stuff
于 2013-03-30T14:56:01.410 回答