ListHelper.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Admin.Core.Common.Helpers
  5. {
  6. public static class ListHelper
  7. {
  8. /// <summary>
  9. /// 将列表转换为树形结构
  10. /// </summary>
  11. /// <typeparam name="T">类型</typeparam>
  12. /// <param name="list">数据</param>
  13. /// <param name="rootWhere">根条件</param>
  14. /// <param name="childsWhere">节点条件</param>
  15. /// <param name="addChilds">添加子节点</param>
  16. /// <param name="entity"></param>
  17. /// <returns></returns>
  18. public static List<T> ToTree<T>(this List<T> list, Func<T, T, bool> rootWhere, Func<T, T, bool> childsWhere, Action<T, IEnumerable<T>> addChilds, T entity = default)
  19. {
  20. var treelist = new List<T>();
  21. //空树
  22. if (list == null || list.Count == 0)
  23. {
  24. return treelist;
  25. }
  26. if (!list.Any(e => rootWhere(entity, e)))
  27. {
  28. return treelist;
  29. }
  30. //树根
  31. if (list.Any(e => rootWhere(entity, e)))
  32. {
  33. treelist.AddRange(list.Where(e => rootWhere(entity, e)));
  34. }
  35. //树叶
  36. foreach (var item in treelist)
  37. {
  38. if (list.Any(e => childsWhere(item, e)))
  39. {
  40. var nodedata = list.Where(e => childsWhere(item, e)).ToList();
  41. foreach (var child in nodedata)
  42. {
  43. //添加子集
  44. var data = list.ToTree(childsWhere, childsWhere, addChilds, child);
  45. addChilds(child, data);
  46. }
  47. addChilds(item, nodedata);
  48. }
  49. }
  50. return treelist;
  51. }
  52. }
  53. }