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