Convert nested foreach-loops with 3 levels to recurrence with n levels

拈花ヽ惹草 提交于 2020-01-03 04:39:07

问题


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?


回答1:


The easiest way is to recurse:

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



回答2:


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



来源:https://stackoverflow.com/questions/12956034/convert-nested-foreach-loops-with-3-levels-to-recurrence-with-n-levels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!