Search code examples
c#.net-framework-version

Iterate through a list that has another list that has another list etc


So I have a list of a specific class I have defined let's say IList<Element> A; the Element class has IList<Children> b;

B list gets it's data from a file. B could have a list that contain a list that contain list etc... "Recursively" or B could have only a single list i.e B the nested lists could vary

I want to iterate on all the lists. is there a possible way to do it?


Solution

  • The naive approach is simply stack recursion - it is fine for many common scenarios:

    class A {
        List<B> _theList;
        void DoTheThing() {
           foreach(var b in _theList) b.DoTheThing();
        }
    }
    class B {
        List<B> _innerItems;
        void DoTheThing() {
            DoTheThingAtThisLevel();
            // and now recurse
            foreach(var inner in _innerItems) inner.DoTheThing();
        }
    }
    

    This can be a problem for very deep lists - as the stack can get too big; in that case, using a local queue or stack and using that for the logical state can avoid that:

    class A {
        List<B> _theList;
        void DoTheThing() {
           var queue = new Queue<B>();
           foreach (var b in _theList)
               queue.Enqueue(b);
           while (queue.Count != 0)
           {
               var b = queue.Dequeue();
               b.ProcessThisLevelOnly();
               // now we do the logical recursion here
               foreach (var inner in b.Items)
                   queue.Enqueue(inner);
           }
        }
    }
    

    You can use a stack vs queue depending on depth-first or breadth-first.