C#构建树形结构数据(全部构建,查找构建)

2019-12-30 18:13:39刘景俊

b.我们暂时id以1开始则pId=0的都为顶级任务

我们首先写一段生成数据的方法:


    public static IList<TreeObejct> GetData(int number = 11)
    {
      IList<TreeObejct> datas = new List<TreeObejct>();
      for (int i = 1; i < number; i++)
      {
        datas.Add(new TreeModel
        {
          id = i.ToString(),
          pId = (i - 1).ToString(),
          name = "节点" + i,
          username = "username" + i,
          password = "password" + i
        });
        datas.Add(new TreeModel
        {
          id = "A" + i.ToString(),
          pId = (i - 1).ToString(),
          name = "节点" + i,
          username = "username" + i,
          password = "password" + i
        });
      }
      return datas;
    }

其次我们定义一些变量:


    private static IList<TreeObejct> models;
    private static IList<TreeObejct> models2;
    private static Thread t1;
    private static Thread t2;
    static void Main(string[] args)
    {
      int count = 21;
      Console.WriteLine("生成任务数:"+count+"个");
     
      Console.Read();
    }

我们再写一个递归获取子节点的递归方法:


    public static IList<TreeObejct> GetChildrens(TreeObejct node)
    {
      IList<TreeObejct> childrens = models.Where(c => c.pId == node.id.ToString()).ToList();
      foreach (var item in childrens)
      {
        item.children = GetChildrens(item);
      }
      return childrens;

    }

编写调用递归方法Recursion:


    public static void Recursion()
    {
      #region 递归遍历
      System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

      sw.Start();

      var mds_0 = models.Where(c => c.pId == "0");//获取顶级任务
      foreach (var item in mds_0)
      {
        item.children = GetChildrens(item);
      }
      sw.Stop();
      Console.WriteLine("----------递归遍历用时:" + sw.ElapsedMilliseconds + "----------线程名称:"+t1.Name+",线程ID:"+t1.ManagedThreadId);

      #endregion
    }

编写main函数启动测试:


    private static IList<TreeObejct> models;
    private static IList<TreeObejct> models2;
    private static Thread t1;
    private static Thread t2;
    static void Main(string[] args)
    {
      int count = 1001;
      Console.WriteLine("生成任务数:"+count+"个");
      models = GetData(count);
     
      t1 = new Thread(Recursion);
     
      t1.Name = "递归遍历";
      t1.Start();
    

      Console.Read();
    }

输出结果:

C#,查找树形结构数据,C#构建树形结构数据