using System.Collections; using System.Collections.Generic; using System.Linq; namespace YBEE.EQM.Core { /// /// 树基类 /// public interface ITreeNode { /// /// 获取节点id /// /// int GetId(); /// /// 获取节点父id /// /// int GetPid(); /// /// 设置Children /// /// void SetChildren(IList children); } /// /// 递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等 /// /// public class TreeBuildUtil where T : ITreeNode { /// /// 顶级节点的父节点Id(默认0) /// private int _rootParentId = 0; /// /// 设置根节点方法 /// 查询数据可以设置其他节点为根节点,避免父节点永远是0,查询不到数据的问题 /// public void SetRootParentId(int rootParentId) { _rootParentId = rootParentId; } /// /// 构造树节点 /// /// /// public List Build(List nodes) { var result = nodes.Where(i => i.GetPid() == _rootParentId).ToList(); result.ForEach(u => BuildChildNodes(nodes, u)); return result; } /// /// 构造子节点集合 /// /// /// private void BuildChildNodes(List totalNodes, T node) { var nodeSubList = totalNodes.Where(i => i.GetPid() == node.GetId()).ToList(); nodeSubList.ForEach(u => BuildChildNodes(totalNodes, u)); node.SetChildren(nodeSubList); } } }