using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Yi.Framework.Infrastructure.Helper { public static class TreeHelper { public static List SetTree(List list, Action action = null!) { if (list is not null && list.Count > 0) { IList result = new List(); long pid = list.Min(m => (m as ITreeModel)!.ParentId); IList t = list.Where(m => (m as ITreeModel)!.ParentId == pid).ToList(); foreach (T model in t) { if (action is not null) { action(model); } result.Add(model); var item = model as ITreeModel; IList children = list.Where(m => (m as ITreeModel)!.ParentId == item!.Id).ToList(); if (children.Count > 0) { SetTreeChildren(list, children, model, action!); } } return result.OrderByDescending(m => (m as ITreeModel)!.OrderNum).ToList(); } return null!; } private static void SetTreeChildren(IList list, IList children, T model, Action action = null!) { var mm = model as ITreeModel; mm!.Children = new List(); foreach (T item in children) { if (action is not null) { action(item); } mm.Children.Add(item); var _item = item as ITreeModel; IList _children = list.Where(m => (m as ITreeModel)!.ParentId == _item!.Id).ToList(); if (_children.Count > 0) { SetTreeChildren(list, _children, item, action!); } } mm.Children = mm.Children.OrderByDescending(m => (m as ITreeModel)!.OrderNum).ToList(); } public interface ITreeModel { public long Id { get; set; } public long ParentId { get; set; } public int OrderNum { get; set; } public List? Children { get; set; } } } }