在 C# 中遍历对象树

编程入门 行业动态 更新时间:2024-10-07 10:14:22
本文介绍了在 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# 中遍历对象树

本文发布于:2023-11-30 06:40:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649049.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!