递归函数以从列表中检索数据 [英] Recursive function to retrieve data from List

查看:81
本文介绍了递归函数以从列表中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一种从列表中获取数据的方法.我的课程结构如下

I have to write a method to get data from a list . My class structure is as below

Class MyNodeItem
{
 public List<MyNodeItem> MyNodeItemList
 {
      get;set;
 }
 public string Text
 {
      get;set;
 }
}

Class MyDataClass
{
  public List <MyNodeItem> MyNodeItems
  {
    get;set;
  }
  public void MyMethod()
  {
   this.MyNodeItems = new List<MyNodeItem>();
   // Here i have code to add items into the myNodeItems
   // it can have nodeitems inside node item
  } 

}

class Client
{
  public void MyClientMethod()
  { 
    MyDataClass obj = new MyDataClass();
    obj.MyMethod();   
  }
}




我应该如何以分层方式检索obj.MyNodeItems.
我需要编写一种方法来获取obj.MyNodeItems并将其以分层方式存储.
我该怎么做
在此先感谢




How shall i retrive the obj.MyNodeItems in Hierarchical manner.
I need to write a method to get the obj.MyNodeItems and store it in Hierarchical manner.
How shall i do that
thanks in advance

推荐答案

public void Iterate(MyNodeItem node)
{
   string s=  node.Text; // whatever

    foreach(MyNodeItem item in node.MyNodeItems)
        Iterate(item);
}



这只是如何递归的经典案例.如果您需要知道父节点,只需传入两个节点,第二个节点的根为null,否则为父节点.



This is just a classic case of how to recurse. If you need to know the parent node, just pass two nodes in, and for the second one, null is the root, otherwise it''s the parent.


典型的分层结构(即树结构)数据模型如下所示(伪代码):

A typical hierarchical (i.e. tree structure) data model looks something like this (pseudo-code):

class Tree<T> {
 TreeNode<T> Root;
}

class TreeNode<T> {
 T Value;
 List<TreeNode<T>> Children;
 TreeNode<T> Parent; // being able to go ''up'' is also useful
}



不知道您实际上要怎么做,我现在无法更加详细.



Without knowing what you actually want to do with it, I can''t be more detailed right now.


这篇关于递归函数以从列表中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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