c# - 递归函数的顺序编号?例如2, 2.1, 2.1.1, 2.2, 2.2.1

标签 c# recursion

我有一个递归函数,可以从数据库中读取文档的“目录”。 我想用反射(reflect)项目在树中位置的文档打印编号,例如

1. First item,
    1.1 Child of first item,
        1.1.1 Child of child of first item,
    1.2 Child of first item,
2. Second item,
    2.1 Child of second item,

等等

目前对此感到很困惑 - 请帮忙?

最佳答案

查看您的代码会很有用。假设数据以某种分层表示形式存储,递归的结构可能如下所示:

void PrintTOC(string prefix, List<Sections> sections) {
  // Iterate over all sections at the current level (e.g. "2")
  for(int i = 0; i<sections.Length; i++) {
    // Get prefix for the current section (e.g. "2.1")
    string num = String.Format("{0}.{1}", prefix, i+1);
    // Write the current section title
    Console.WriteLine("{0} {1}", num, sections[i].Titles);

    // Recursively process all children, passing "2.1" as the prefix
    if (sections[i].Children != null)
      PrintTOC(num, sections[i].Children);
  }
}

这保留了一个包含父部分索引的prefix 参数。当前部分中的所有数字都附加在此前缀之后。

关于c# - 递归函数的顺序编号?例如2, 2.1, 2.1.1, 2.2, 2.2.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2668007/

相关文章:

java - 为什么我的递归不起作用? ( java )

c - 正值输入 C

c# - 如何使用 C# 对值进行数字排序?

c# - 如何使用 requireSSL ="true"修复 CSRF 和 [加密 session (SSL) Cookie 中缺少安全属性] 问题?

c - 在 C 中使用递归反转数字函数

visual-studio-2010 - 递归方法

c# - 绑定(bind)到函数后,下拉列表在 postpack 后重置

c# - DateTime.ParseExact() 比 DateTime.Parse() 快吗

c# - 当存在多个同名节点时,如何编辑 XML 中特定节点的值?

javascript - Vue JS 中的递归方法