递归函数的连续编号?例如2,2.1,2.1.1,2.2,2.2.1

Pet*_*ete 3 c# recursion

我有一个递归函数从数据库中读取文档的"目录".我想用反映项目在树中的位置的文档打印编号,例如

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,
Run Code Online (Sandbox Code Playgroud)

等等

此刻相当难倒 - 请帮忙吗?

Tom*_*cek 5

查看代码会很有用.假设数据存储在某种层次结构表示中,递归的结构可能如下所示:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这将保留包含父节的索引的前缀参数.当前部分中的所有数字都附加在此前缀之后.