C# 递归函数的顺序编号?e、 g.2、2.1、2.1.1、2.2、2.2.1

C# 递归函数的顺序编号?e、 g.2、2.1、2.1.1、2.2、2.2.1,c#,recursion,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, 等等 目前对此相当困惑-请帮助?查看您的代码会很有用。假设数据存储在某种层

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

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);
  }
}
void PrintTOC(字符串前缀,列表部分){
//迭代当前级别的所有部分(例如“2”)
对于(int i=0;i,只需在函数中包含一个“path”参数,并在运行时添加到其中。伪代码:

function print_rec(String path, Node node) {
  print(path + node.title)
  for (int i=1; i<=node.children.length; i++) {
    print_rec(path+"."+i, node.children[i])
  }
}
函数打印记录(字符串路径,节点){
打印(路径+节点标题)

对于(int i=1;i您的数据库平台是什么?如果您使用的是SQL Server 2005或更高版本,则可以使用单个CTE查询从“树”表(带有自引用键的表)中获取此类路径。(SQL Server中也有基于XML的运行递归查询的技术。)


否则,您将不得不在客户端代码中执行递归,正如其他人所建议的那样。在这种情况下,您可能需要在开始递归之前考虑所有相关数据,并使用对象来遍历结构。这样您就可以避免对数据库的大量查询。

@ Pete:您需要提供最初存储此数据的方式?它是以层次结构树的形式返回,还是以与其他行相关的行列表的形式返回?数据以引用父行+显示顺序的方式存储在行中。感谢您的格式清理,CAbbott!