Nicolas Martel
Nicolas Martel

Reputation: 1721

C# recursively go through items in a List of T where T has a List of T

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.

Upvotes: 0

Views: 304

Answers (4)

Blau
Blau

Reputation: 5762

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}
}

Upvotes: 1

Mbt925
Mbt925

Reputation: 1346

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);
}

Upvotes: 2

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32501

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.

Upvotes: 1

RyPope
RyPope

Reputation: 2715

I would recommend the use of the foreach. For example

foreach(List node in T)
    foreach(List folders in node)
        //do stuff

Upvotes: 0

Related Questions