ITree.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace Masuit.Tools.Core.Models
  4. {
  5. /// <summary>
  6. /// 树形实体接口
  7. /// </summary>
  8. /// <typeparam name="T"></typeparam>
  9. public interface ITree<T> where T : ITree<T>
  10. {
  11. /// <summary>
  12. /// 名字
  13. /// </summary>
  14. public string Name { get; set; }
  15. /// <summary>
  16. /// 父节点
  17. /// </summary>
  18. public T Parent { get; set; }
  19. /// <summary>
  20. /// 子级
  21. /// </summary>
  22. public ICollection<T> Children { get; set; }
  23. /// <summary>
  24. /// 所有子级
  25. /// </summary>
  26. public ICollection<T> AllChildren => GetChildren(this);
  27. /// <summary>
  28. /// 所有父级
  29. /// </summary>
  30. public ICollection<T> AllParent => GetParents(this);
  31. /// <summary>
  32. /// 是否是根节点
  33. /// </summary>
  34. public bool IsRoot => Parent == null;
  35. /// <summary>
  36. /// 是否是叶子节点
  37. /// </summary>
  38. public bool IsLeaf => Children.Count == 0;
  39. /// <summary>
  40. /// 深度
  41. /// </summary>
  42. public int Level => IsRoot ? 0 : Parent.Level + 1;
  43. /// <summary>
  44. /// 节点路径(UNIX路径格式,以“/”分隔)
  45. /// </summary>
  46. public string Path => GetFullPath(this);
  47. private string GetFullPath(ITree<T> c) => c.Parent != null ? GetFullPath(c.Parent) + "/" + c.Name : c.Name;
  48. /// <summary>
  49. /// 递归取出所有下级
  50. /// </summary>
  51. /// <param name="t"></param>
  52. /// <returns></returns>
  53. private List<T> GetChildren(ITree<T> t)
  54. {
  55. return t.Children.Union(t.Children.Where(c => c.Children.Any()).SelectMany(tree => GetChildren(tree))).ToList();
  56. }
  57. /// <summary>
  58. /// 递归取出所有下级
  59. /// </summary>
  60. /// <param name="t"></param>
  61. /// <returns></returns>
  62. private List<T> GetParents(ITree<T> t)
  63. {
  64. var list = new List<T>() { t.Parent };
  65. return t.Parent != null ? list.Union(GetParents(t.Parent)).ToList() : list;
  66. }
  67. }
  68. }