Tree构建
后端构建一颗树,返回前端,如下所示。
[ { "Guid": "0ada72a1-0c29-4a49-80f2-adeeae4409bd", "id": 1, "text": "苏泊尔", "children": [ { "Guid": "27be157d-46c1-476d-abb0-3b08cf9a55a5", "id": 3, "text": "车间一一", "children": [] }, { "Guid": "0e107c67-5933-4cec-bd05-b1c4ffff7f9d", "id": 2, "text": "车间二", "children": [ { "Guid": "d3bf0d47-98e7-4dd7-aac5-ab0aeb7a6486", "id": 5, "text": "A2班组", "children": [] }, { "Guid": "2ada1f14-186d-4726-9740-ee752363b2fc", "id": 4, "text": "A!班组", "children": [] } ] } ] } ]
这里我通过递归方法将树输出。
/// <summary> /// 递归构建树 /// </summary> /// <param name="sid">父id</param> /// <returns></returns> List<DepartmentNodeModel> Tree(int sid) { List<Departments> departmentsList = DepartmentsData.QueryDepartments(d => d.Supdeptid == sid); List<DepartmentNodeModel> departmentNodeTree = new List<DepartmentNodeModel>(); foreach (Departments d in departmentsList) { DepartmentNodeModel departmentNode = new DepartmentNodeModel(); departmentNode.Guid = d.ID; departmentNode.id = d.Deptid; departmentNode.text = d.Deptname; departmentNode.children = Tree(d.Deptid); departmentNodeTree.Add(departmentNode); } return departmentNodeTree; } /// <summary> /// 获取部门树 /// </summary> /// <returns></returns> [HttpGet, Route("GetDepartmentsTree")] public List<DepartmentNodeModel> GetDepartmentsTree() { //LIST => TREE List<DepartmentNodeModel> departmentNodeTree = Tree(-1); return departmentNodeTree; }
能在项目中用到递归还是蛮兴奋的,哈哈