TreeUtil.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // <author></author>
  2. // <date></date>
  3. // <description></description>
  4. using ERP.Framework.WebApi;
  5. namespace ERP.Framework.Utils
  6. {
  7. public class TreeUtil
  8. {
  9. public static List<T> Build<T>(List<T> list) where T : TreeEntity<T>
  10. {
  11. var result = new List<T>();
  12. var tempIdList = new List<long>();
  13. foreach (var item in list)
  14. {
  15. tempIdList.Add(item.Id);
  16. }
  17. foreach (var item in list)
  18. {
  19. if (!tempIdList.Contains(item.ParentId))
  20. {
  21. RecursionFn(list, item);
  22. result.Add(item);
  23. }
  24. }
  25. if (result.Count == 0)
  26. {
  27. result = list;
  28. }
  29. return result;
  30. }
  31. private static List<T> GetChildList<T>(List<T> list, T t) where T : TreeEntity<T>
  32. {
  33. return list.Where(l => l.ParentId == t.Id).ToList();
  34. }
  35. private static void RecursionFn<T>(List<T> list, T t) where T : TreeEntity<T>
  36. {
  37. List<T> childList = GetChildList(list, t);
  38. t.Children = childList;
  39. foreach (var tChild in childList)
  40. {
  41. if (GetChildList(list, t).Count > 0)
  42. {
  43. RecursionFn(list, tChild);
  44. }
  45. }
  46. }
  47. }
  48. }