TreeBuildUtil.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace YBEE.EQM.Core
  5. {
  6. /// <summary>
  7. /// 树基类
  8. /// </summary>
  9. public interface ITreeNode
  10. {
  11. /// <summary>
  12. /// 获取节点id
  13. /// </summary>
  14. /// <returns></returns>
  15. int GetId();
  16. /// <summary>
  17. /// 获取节点父id
  18. /// </summary>
  19. /// <returns></returns>
  20. int GetPid();
  21. /// <summary>
  22. /// 设置Children
  23. /// </summary>
  24. /// <param name="children"></param>
  25. void SetChildren(IList children);
  26. }
  27. /// <summary>
  28. /// 递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等
  29. /// </summary>
  30. /// <typeparam name="T"></typeparam>
  31. public class TreeBuildUtil<T> where T : ITreeNode
  32. {
  33. /// <summary>
  34. /// 顶级节点的父节点Id(默认0)
  35. /// </summary>
  36. private int _rootParentId = 0;
  37. /// <summary>
  38. /// 设置根节点方法
  39. /// 查询数据可以设置其他节点为根节点,避免父节点永远是0,查询不到数据的问题
  40. /// </summary>
  41. public void SetRootParentId(int rootParentId)
  42. {
  43. _rootParentId = rootParentId;
  44. }
  45. /// <summary>
  46. /// 构造树节点
  47. /// </summary>
  48. /// <param name="nodes"></param>
  49. /// <returns></returns>
  50. public List<T> Build(List<T> nodes)
  51. {
  52. var result = nodes.Where(i => i.GetPid() == _rootParentId).ToList();
  53. result.ForEach(u => BuildChildNodes(nodes, u));
  54. return result;
  55. }
  56. /// <summary>
  57. /// 构造子节点集合
  58. /// </summary>
  59. /// <param name="totalNodes"></param>
  60. /// <param name="node"></param>
  61. private void BuildChildNodes(List<T> totalNodes, T node)
  62. {
  63. var nodeSubList = totalNodes.Where(i => i.GetPid() == node.GetId()).ToList();
  64. nodeSubList.ForEach(u => BuildChildNodes(totalNodes, u));
  65. node.SetChildren(nodeSubList);
  66. }
  67. }
  68. }