zoukankan      html  css  js  c++  java
  • C# 树形结构tree拼接

    实体类:

    public class Project
    {
        public Project()
        {
            children = new List<Project>();
        }
        public int id { get; set; }
        public int parentId { get; set; }
        public string name { get; set; }
        public List<Project> children { get; set; }
    }
    • 所有表结构数据
    idparentIdname
    1 -1 name1
    2 1 name2
    3 1 name3
    4 2 name4
    • 查询所有数据
      public List<Project> GetProjectTree()
      {
      List<Project> list=_projectService.GetAll().ToList();//获取所有数据,即上述列出的数据
      List<Project> data = new List<Project>();
      data.AddRange(rs.Where(p => p.parentId == -1).ToList());//将一级数据加入data中
      foreach (var item in data)
      {
            AddProjectChildren(item, rs);
      }
      return data;
      }
    • AddProjectChildren 递归函数
      //关键1: 传入的model是对象,对象修改会直接影响引用的对象
      //关键2: 递归调用,直到传入的列表为空
      private Project AddProjectChildren(Project model, List<Project> typeList)
      {
          var treeList = new List<Project>();
          var list = typeList.Where(p => p.parentId == model.id).ToList();
          if (list.Count == 0) return null;
          foreach (var item in list)
          {
                treeList.Add(item);
                typeList.Remove(item);
           }
          model.children = treeList;
          foreach (var children in model.children)
          {
                AddProjectChildren(children, typeList);
          }
       return model;
      }

      结果

      [
          {
              "children": [
                  {
                      "children": [
                          {
                            "children": [],
                            "id": 4,
                            "parentId": 2,
                            "name": "name4",
                        },
                      ],
                      "id": 2,
                      "parentId": 1,
                      "name": "name2",
                  },
                  {
                      "children": [],
                      "id": 3,
                      "parentId": 1,
                      "name": "name3",
                  }
              ],
              "id": 1,
              "parentId": -1,
              "name": "name1",
          }
      ]
  • 相关阅读:
    vue-cli(vue脚手架)简单流程
    windows环境之node.js安装与环境配置
    fiddler的下载和简单使用
    Linux 配置nginx 代理tomcat,配置ssl
    来聊一聊导出数据问题
    作为一个开发人员应该具备怎么样技术栈和职业素养
    NODEJS的误打误撞
    聊一下程序员的日常
    openstack安装部署私有云详细图文
    openstack:OpenStack架构详解,
  • 原文地址:https://www.cnblogs.com/shijiehaiyang/p/13691171.html
Copyright © 2011-2022 走看看