Iterate through nested list with many layers

烂漫一生 提交于 2021-02-20 03:43:42

问题


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

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