问题
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