用递归形成树结构数据
定义一个树形实体
public class orgTrees { public orgTrees() { this.Children = new List<orgTrees>(); } public int Id { get; set; } public int FatherId { get; set; } public string Name { get; set; } public int Lever { get; set; } public bool HasChildren { get; set; } public string OrgCode; public int OrgType; public List<orgTrees> Children { get; set; } }
开始递归方法
1 /// <summary> 2 /// 获取组织层级树 3 /// </summary> 4 /// <returns></returns> 5 public AjaxResponse<orgTrees> GetOrgTrees() 6 { 7 var list = new List<orgTrees>(); 8 var orgLayerList = _organizeProxy.ListOrgInfoForManage(); 9 10 var dic = new Dictionary<int, orgTrees>(orgLayerList.Count); 11 foreach (var item in orgLayerList) 12 { 13 dic.Add(item.Info.Id, new orgTrees 14 { 15 Id = item.Info.Id, 16 FatherId = item.Info.FatherId, 17 Name = item.Info.Name.GetValueByLanId(WorkContext.WorkingLanguage.Id), 18 Lever = item.Layer, 19 OrgCode = item.Info.OrgCode, 20 OrgType = item.Info.OrgType, 21 }); 22 } 23 24 //根节点 25 var rootNode = orgLayerList.Where(x => x.Info.FatherId.Equals(-1)).First(); 26 var model = new orgTrees(); 27 model.Id = rootNode.Info.Id; 28 model.FatherId = rootNode.Info.FatherId; 29 model.Name = rootNode.Info.Name.GetValueByLanId(WorkContext.WorkingLanguage.Id); 30 model.Lever = rootNode.Layer; 31 model.OrgCode = rootNode.Info.OrgCode; 32 model.OrgType = rootNode.Info.OrgType; 33 model.HasChildren = rootNode.HasChildren; 34 CreatTree(model.Id, model, orgLayerList); 35 return new AjaxResponse<orgTrees>(model); 36 } 37 //生成树的方法 38 public void CreatTree(int parentId, orgTrees tree, LayerList<OrganizeInfo> laerList) 39 { 40 //获取子节点 41 var childrenNode = laerList.ToList().FindAll(x => x.Info.FatherId == Convert.ToInt32(parentId)); 42 //如果没有字节点了,那就返回空 43 if (childrenNode.Count == 0) return; 44 List<orgTrees> nodeTrees = new List<orgTrees>(); 45 for (int i = 0; i < childrenNode.Count; i++) 46 { 47 orgTrees node = new orgTrees(); 48 node.Id = childrenNode[i].Info.Id; 49 node.Name = childrenNode[i].Info.Name.GetValueByLanId(WorkContext.WorkingLanguage.Id); 50 node.FatherId = childrenNode[i].Info.FatherId; 51 node.Lever = childrenNode[i].Layer; 52 node.OrgCode = childrenNode[i].Info.OrgCode; 53 node.OrgType = childrenNode[i].Info.OrgType; 54 node.HasChildren = childrenNode[i].HasChildren; 55 //递归 56 CreatTree(childrenNode[i].Info.Id, node, laerList); 57 nodeTrees.Add(node); 58 } 59 tree.Children = nodeTrees; //由于对象是引用类型,因为可以改变参数的值 60 }
说下思路就是 先把根节点找出来,然后寻找根节点的子节点 然后递归循环子节点,寻找子节点的子节点
最后生成的是就是