迭代具有多层的嵌套列表 [英] Iterate through nested list with many layers

查看:50
本文介绍了迭代具有多层的嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情况:您有一个集合,并且在该集合内是特定的对象.这些对象还拥有一个集合,并且在这些集合内有更多相同的对象.这是一个多层嵌套的集合.

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.

推荐答案

您应该研究编写递归方法.(互联网上有很多有关此的信息)

You should look into writing a recursive method. (There is lots of information on the Internet about it)

本质上,递归方法是调用自身的方法.

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);
}

请注意不断增长的堆栈

这篇关于迭代具有多层的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆