0

I want to convert the following code to handle more than 3 foreach-levels.

internal static void CreateLevel(LevelObject levelObject)
{
   foreach(LevelObject l1 in levelObject.LevelObjects)
   {
      foreach(LevelObject l2 in l1.LevelObjects)
      {
         foreach(LevelObject l3 in l2.LevelObjects)
         {
            AddEntities(l3);
         }
         AddEntities(l2);
      }
      AddEntities(l1);
   }
}

Every LevelObject has a collection of child-level-objects, a collection of entities and a parent-level-object. I need this to convert an object-structure to a filter. Anyone has an idea how to convert this?

Otiel
  • 18,404
  • 16
  • 78
  • 126
Tomtom
  • 9,087
  • 7
  • 52
  • 95

2 Answers2

8

The easiest way is to recurse:

internal static void CreateLevel(LevelObject levelObject) {
    foreach (var l in levelObject.LevelObjects) {
        CreateLevel(l);
        AddEntities(l);
    }
}
erikkallen
  • 33,800
  • 13
  • 85
  • 120
  • Ok, but with no bounding case, this might go wrong. Depends what data is thrown at it. Might be better to include a level so we can stop stop recursing at depth n – spender Oct 18 '12 at 13:41
  • But he probably wants to change his code because he wants more than 3 levels. – erikkallen Oct 18 '12 at 13:42
  • Saw that and corrected to `n`, but without further thought of bounding-cases, this *could* stackoverflow. It **will** SO if the graph is cyclic. – spender Oct 18 '12 at 13:43
0

Using your code...

internal static void CreateLevel(LevelObject levelObject)
{
   foreach(LevelObject l1 in levelObject.LevelObjects)
   {
      CreateLevel(l1.LevelObjects);
      AddEntities(l1);
   }
}

Will accomplish the same goal

thaBadDawg
  • 5,160
  • 6
  • 35
  • 44