问题
Consider the scenario where you have a collection, and inside that collection are particular objects. Those objects also hold a collection, and inside those collections are more of the same objects. It's a nested collection with many layers.
List<WorkItemClassificationNode> items;
List<WorkItemClassificationNode> subItems = items.Children;
List<WorkItemClassificationNode> subSubItems = subItems.Children;
// etc
I just want a method to iterate through each of those layers so the same logic is applied to each item, but I can't think of a straightforward way of doing this without writing loads of nested loops.
回答1:
You should look into writing a recursive method. (There is lots of information on the Internet about it)
Essentially, a recursive method is a method that calls itself.
void DoThing(WorkItemClassificationNode node)
{
if (node == null)
return;
//Do something with node
if (node.Children == null)
return;
foreach(var child in node.Children)
DoThing(child);
}
Just be aware of the ever growing stack!
来源:https://stackoverflow.com/questions/48520080/iterate-through-nested-list-with-many-layers