实体类:
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; } }
- 所有表结构数据
id | parentId | name |
---|---|---|
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", } ]