基础服务api
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

82 lines
2.3 KiB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace BPA.SAAS.Manage.Comm.Util
  8. {
  9. /// <summary>
  10. /// 树基类
  11. /// </summary>
  12. public interface ITreeNode
  13. {
  14. /// <summary>
  15. /// 获取节点id
  16. /// </summary>
  17. /// <returns></returns>
  18. string GetId();
  19. /// <summary>
  20. /// 获取节点父id
  21. /// </summary>
  22. /// <returns></returns>
  23. string GetPid();
  24. /// <summary>
  25. /// 设置Children
  26. /// </summary>
  27. /// <param name="children"></param>
  28. void SetChildren(IList children);
  29. }
  30. /// <summary>
  31. /// 递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等
  32. /// </summary>
  33. /// <typeparam name="T"></typeparam>
  34. public class TreeBuildUtil<T> where T : ITreeNode
  35. {
  36. /// <summary>
  37. /// 顶级节点的父节点Id(默认00000000-0000-0000-0000-000000000000)
  38. /// </summary>
  39. private readonly string _rootParentId = "0";
  40. /// <summary>
  41. /// 构造树节点
  42. /// </summary>
  43. /// <param name="nodes"></param>
  44. /// <returns></returns>
  45. public List<T> Build(List<T> nodes)
  46. {
  47. nodes.ForEach(u => BuildChildNodes(nodes, u, new List<T>()));
  48. var result = new List<T>();
  49. nodes.ForEach(u =>
  50. {
  51. if (_rootParentId == u.GetPid())
  52. result.Add(u);
  53. });
  54. return result;
  55. }
  56. /// <summary>
  57. /// 构造子节点集合
  58. /// </summary>
  59. /// <param name="totalNodes"></param>
  60. /// <param name="node"></param>
  61. /// <param name="childNodeList"></param>
  62. private void BuildChildNodes(List<T> totalNodes, T node, List<T> childNodeList)
  63. {
  64. var nodeSubList = new List<T>();
  65. totalNodes.ForEach(u =>
  66. {
  67. if (u.GetPid().Equals(node.GetId()))
  68. nodeSubList.Add(u);
  69. });
  70. nodeSubList.ForEach(u => BuildChildNodes(totalNodes, u, new List<T>()));
  71. childNodeList.AddRange(nodeSubList);
  72. node.SetChildren(childNodeList);
  73. }
  74. }
  75. }