using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace Masuit.Tools.Core.Models { /// /// 树形实体接口 /// /// public interface ITree where T : ITree { /// /// 名字 /// public string Name { get; set; } /// /// 父节点 /// public T Parent { get; set; } /// /// 子级 /// public ICollection Children { get; set; } /// /// 所有子级 /// [NotMapped] public ICollection AllChildren => GetChildren(this); /// /// 所有父级 /// [NotMapped] public ICollection AllParent => GetParents(this); /// /// 是否是根节点 /// [NotMapped] public bool IsRoot => Parent == null; /// /// 是否是叶子节点 /// [NotMapped] public bool IsLeaf => Children.Count == 0; /// /// 深度 /// [NotMapped] public int Level => IsRoot ? 0 : Parent.Level + 1; /// /// 节点路径(UNIX路径格式,以“/”分隔) /// [NotMapped] public string Path => GetFullPath(this); private string GetFullPath(ITree c) => c.Parent != null ? GetFullPath(c.Parent) + "/" + c.Name : c.Name; /// /// 递归取出所有下级 /// /// /// private List GetChildren(ITree t) { return t.Children.Union(t.Children.Where(c => c.Children.Any()).SelectMany(tree => GetChildren(tree))).ToList(); } /// /// 递归取出所有上级 /// /// /// private List GetParents(ITree t) { var list = new List() { t.Parent }; return t.Parent != null ? list.Union(GetParents(t.Parent)).ToList() : list; } } }