C#以输出树结构的形式打印数据

时间:2015-11-20 11:06:58

标签: c#

我有一个数据集:List<school>学校。我想以输出树的形式打印数据。

如何按id对值进行分组,以这种格式显示:

-Department

- 教育

---区

----公立学校

----- School1

----- School4

----私立学校

----- College5

----- College3

----- College2

    List<school> Schools = new List<school>()
    { 
       new school() { id = 1, Description = "Department", ParentID = null},
       new school() { id = 2, Description = "Education", ParentID = 1},
       new school() { id = 3, Description = "District", ParentID = 2},
       new school() { id = 4, Description = "Public Schools", ParentID = 3},
       new school() { id = 5, Description = "College2", ParentID = 6},
       new school() { id = 6, Description = "Private Schools", ParentID = 3},
       new school() { id = 7, Description = "School4", ParentID = 4},
       new school() { id = 8, Description = "College5", ParentID = 6},
       new school() { id = 9, Description = "School1", ParentID = 4},
       new school() { id = 9, Description = "College3", ParentID = 6}
    };


foreach(var _school in Schools)
{

  if(_school.ParentID != null)
  {
     for (int i = 0; i < Schools.Count; i++)
     {
            IEnumerable<school> query = Schools.Where(s => s.ParentID + i == s.ID);

            var dash = "-";
            foreach (var school in query)
            {
                dash += dash;
                Console.WriteLine( dash + t.Description);
            }
      };

  }
  else
  {
     Console.WriteLine("-" + _school.Description);
      };
};

2 个答案:

答案 0 :(得分:0)

您的数据结构算法必须如下:

public void Print(List<school> nodes, int? parentId, string prefix)
{
    var nodesToPrint = nodes.Where(x => x.ParentID == parentId);

    foreach (var item in nodesToPrint)
    {
        Console.WriteLine(prefix + item.Description);

        Print(nodes, item.id, prefix + prefix[0]);
    }
}

并从代码中打印出来:

Print(Schools, null, "-");

但我想建议您将树存储为逻辑树。 例如:

public class school
{
    public string Description { get; set; }
    public List<school> Childs { get; set; }
}

在此课程中使用打印方法:

public void Print(string prefix = string.Empty)
{
    Console.WriteLine(prefix + this.Description);

    if (this.Childs != null)
    {
        foreach (var item in this.Childs)
        {
            item.Print(prefix + "-");
        }
    }
}

因此,如果您只有一个父项,则可以打印整个树:

var sch = //your method to get schools
sch.Print();

答案 1 :(得分:0)

你可以使用递归方法做这样的事情:

在你的主要功能中:

var root = schools.SingleOrDefault(x => x.ParentID == null);
if(root != null) { 
   PrintSub(schools, root, 1);
}

一个(静态)递归函数:

private static void PrintSub(List<School> schools, School current, int level)
{
   Console.WriteLine(new string('-', level) + current.Description);
   var children = schools.Where(x => x.ParentID == current.id);
   ++level;
   foreach (var school in children)
   {
      PrintSub(schools, school, level);
   }
}