ITree.cs 2.3 KB

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