C# 树形结构tree拼接

2020-12-22 01:27

阅读:607

标签:service   each   where   vat   get   project   add   调用   span   

实体类:

public class Project
{
    public Project()
    {
        children = new List();
    }
    public int id { get; set; }
    public int parentId { get; set; }
    public string name { get; set; }
    public List children { get; set; }
}
  • 所有表结构数据
id parentId name
1 -1 name1
2 1 name2
3 1 name3
4 2 name4
  • 查询所有数据
    public List GetProjectTree()
    {
    List list=_projectService.GetAll().ToList();//获取所有数据,即上述列出的数据
    List data = new List();
    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 typeList)
    {
        var treeList = new List();
        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",
        }
    ]

     

C# 树形结构tree拼接

标签:service   each   where   vat   get   project   add   调用   span   

原文地址:https://www.cnblogs.com/shijiehaiyang/p/13691171.html


评论


亲,登录后才可以留言!