using System.Collections.Generic; namespace learun.util { /// /// 版 本 EasyCode EC管理后台 /// Copyright (c) 2019-present EC管理有限公司 /// 创建人:tobin /// 日 期:2019.09.10 /// 描 述:树结构数据 /// public static class TreeDataMake { /// /// 树形数据转化 /// /// 数据 /// 父级id /// public static List ToTree(this List list, string parentId = "") { Dictionary> childrenMap = new Dictionary>(); Dictionary parentMap = new Dictionary(); List res = new List(); //首先按照 foreach (var node in list) { node.hasChildren = false; node.complete = true; // 注册子节点映射表 if (!childrenMap.ContainsKey(node.parentId)) { childrenMap.Add(node.parentId, new List()); } else if (parentMap.ContainsKey(node.parentId)) { parentMap[node.parentId].hasChildren = true; } childrenMap[node.parentId].Add(node); // 注册父节点映射节点表 parentMap.Add(node.id, node); // 查找自己的子节点 if (!childrenMap.ContainsKey(node.id)) { childrenMap.Add(node.id, new List()); } else { node.hasChildren = true; } node.ChildNodes = childrenMap[node.id]; } if (string.IsNullOrEmpty(parentId)) { // 获取祖先数据列表 foreach (var item in childrenMap) { if (!parentMap.ContainsKey(item.Key)) { res.AddRange(item.Value); } } } else { if (childrenMap.ContainsKey(parentId)) { return childrenMap[parentId]; } else { return new List(); } } return res; } /// /// 树形数据转化 /// /// 数据 /// public static List> ToTree(this List> list) where T : class { Dictionary>> childrenMap = new Dictionary>>(); Dictionary> parentMap = new Dictionary>(); List> res = new List>(); //首先按照 foreach (var node in list) { // 注册子节点映射表 if (!childrenMap.ContainsKey(node.parentId)) { childrenMap.Add(node.parentId, new List>()); } childrenMap[node.parentId].Add(node); // 注册父节点映射节点表 parentMap.Add(node.id, node); // 查找自己的子节点 if (!childrenMap.ContainsKey(node.id)) { childrenMap.Add(node.id, new List>()); } node.ChildNodes = childrenMap[node.id]; } // 获取祖先数据列表 foreach (var item in childrenMap) { if (!parentMap.ContainsKey(item.Key)) { res.AddRange(item.Value); } } return res; } /// /// 树形数据转化 /// /// 数据 /// 父级id /// public static List ToMenuTree(this List list, string parentId = "") { Dictionary> childrenMap = new Dictionary>(); Dictionary parentMap = new Dictionary(); List res = new List(); //首先按照 foreach (var node in list) { node.hasChildren = false; node.complete = true; // 注册子节点映射表 if (!childrenMap.ContainsKey(node.parentId)) { childrenMap.Add(node.parentId, new List()); } else if (parentMap.ContainsKey(node.parentId)) { parentMap[node.parentId].hasChildren = true; } childrenMap[node.parentId].Add(node); // 注册父节点映射节点表 parentMap.Add(node.id, node); // 查找自己的子节点 if (!childrenMap.ContainsKey(node.id)) { childrenMap.Add(node.id, new List()); } else { node.hasChildren = true; } node.ChildNodes = childrenMap[node.id]; } if (string.IsNullOrEmpty(parentId)) { // 获取祖先数据列表 foreach (var item in childrenMap) { if (!parentMap.ContainsKey(item.Key)) { res.AddRange(item.Value); } } } else { if (childrenMap.ContainsKey(parentId)) { return childrenMap[parentId]; } else { return new List(); } } return res; } } }