在 C# 中遍历对象树 [英] Traversing a tree of objects in c#

查看:27
本文介绍了在 C# 中遍历对象树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由多个对象组成的树,其中每个对象都有一个名称(string)、id(int)和可能的子元素数组相同的类型.如何遍历整个树并打印出所有的 ID 和名称?

I have a tree that consists of several objects, where each object has a name (string), id (int) and possibly an array of children that are of the same type. How do I go through the entire tree and print out all of the ids and names?

我是编程新手,坦率地说,我无法理解这个问题,因为我不知道有多少个级别.现在我正在使用 foreach 循环来直接获取根目录下的父对象,但这意味着我无法获取子对象.

I'm new to programming and frankly, I'm having trouble wrapping my head around this because I don't know how many levels there are. Right now I'm using a foreach loop to fetch the parent objects directly below the root, but this means I cannot get the children.

推荐答案

一个使用递归的算法是这样的:

An algorithm which uses recursion goes like this:

printNode(Node node)
{
  printTitle(node.title)
  foreach (Node child in node.children)
  {
    printNode(child); //<-- recursive
  }
}

这里有一个版本,它也跟踪递归嵌套的深度(即我们是否打印根的子节点、孙子节点、曾孙子节点等):

Here's a version which also keeps track of how deeply nested the recursion is (i.e. whether we're printing children of the root, grand-children, great-grand-children, etc.):

printRoot(Node node)
{
  printNode(node, 0);
}

printNode(Node node, int level)
{
  printTitle(node.title)
  foreach (Node child in node.children)
  {
    printNode(child, level + 1); //<-- recursive
  }
}

这篇关于在 C# 中遍历对象树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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