浏览嵌套数据结构 [英] Go through a nested data structure

查看:101
本文介绍了浏览嵌套数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种自己的树形结构。



如你所见,这可以有任何深度。但是,我现在遇到了这个结构的问题。使用foreach循环,我总是只能搜索一个列表,但不能搜索子列表。你会怎么做?



我尝试过:



I have a kind of own tree structure.

As you can see, this can have any depth. However, I have problems going through this structure now. With foreach loops, I can always search only one list, but not the children lists. How would you do that?

What I have tried:

public class MyClass
{
   public string Name{ get; set; }
   public List<MyClass> Children { get; set; }
}

推荐答案

这是一个英语网站,我们只接受并回答该语言的问题。将来,请使用Google翻译帮助发布您的问题 - 它做得非常好!



处理深度未知的列表列表的最简单方法是使用递归:

This is an English language site, and we only accept and answer questions in that language. In future, please use Google Translate to help post your question - it does a pretty good job!

The easiest way to process lists of lists where the depth is unknown is to use recursion:
public void Process(MyClass mc)
   {
   ... Process instance mc ...
   if (mc.Children != null)
      {
      foreach (MyClass child in mc.Children)
         {
         Process(child);
         }
      }
   }

将其传递给主要项目,它将对每个孩子执行相同的操作,无论深度如何。

Pass it the "main item" and it will perform the same operation on each child, regardless of the depth.


给定 search()函数:

Given a search() function :
public MyClass search(Myclass node)
{
    foreach(var c in node.Children)
    {
       // search code here if found
       // return c

       // else go down
       var ret = search(c);
       if(ret != null)
          return ret;
    }
    return null;
}

您可以切换块进行深度优先搜索。

You can switch the blocks to do depth first search.


这篇关于浏览嵌套数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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