using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace IRaCIS.Core.Infrastructure.Extention { public static class ListTreeExtensions { /// /// 将列表转换为树形结构 /// /// 类型 /// 数据 /// 根条件 /// 节点条件 /// 添加子节点 /// /// public static List ToTree(this List list, Func rootWhere, Func childsWhere, Action> addChilds, Func orderSelector, T childEntity = default) { if (rootWhere is null) { throw new ArgumentNullException(nameof(rootWhere)); } if (childsWhere is null) { throw new ArgumentNullException(nameof(childsWhere)); } if (addChilds is null) { throw new ArgumentNullException(nameof(addChilds)); } if (orderSelector is null) { throw new ArgumentNullException(nameof(orderSelector)); } var treelist = new List(); //空树 if (list == null || list.Count == 0) { return treelist; } if (!list.Any(e => rootWhere(childEntity, e))) { return treelist; } //树根 if (list.Any(e => rootWhere(childEntity, e))) { treelist.AddRange(list.Where(e => rootWhere(childEntity, e)).OrderBy(orderSelector)); } //树叶 item 是根 foreach (var item in treelist) { if (list.Any(e => childsWhere(item, e))) { var nodedata = list.Where(e => childsWhere(item, e)).OrderBy(orderSelector).ToList(); foreach (var child in nodedata) { //添加子集 var data = list.ToTree(childsWhere, childsWhere, addChilds, orderSelector, child); addChilds(child, data); } addChilds(item, nodedata); } } return treelist; } } }