爱思开
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.5 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. namespace NFine.Code
  6. {
  7. public static class TreeQuery
  8. {
  9. public static List<T> TreeWhere<T>(this List<T> entityList, Predicate<T> condition, string keyValue = "F_Id", string parentId = "F_ParentId") where T : class
  10. {
  11. List<T> locateList = entityList.FindAll(condition);
  12. var parameter = Expression.Parameter(typeof(T), "t");
  13. List<T> treeList = new List<T>();
  14. foreach (T entity in locateList)
  15. {
  16. treeList.Add(entity);
  17. string pId = entity.GetType().GetProperty(parentId).GetValue(entity, null).ToString();
  18. while (true)
  19. {
  20. if (string.IsNullOrEmpty(pId) && pId == "0")
  21. {
  22. break;
  23. }
  24. Predicate<T> upLambda = (Expression.Equal(parameter.Property(keyValue), Expression.Constant(pId))).ToLambda<Predicate<T>>(parameter).Compile();
  25. T upRecord = entityList.Find(upLambda);
  26. if (upRecord != null)
  27. {
  28. treeList.Add(upRecord);
  29. pId = upRecord.GetType().GetProperty(parentId).GetValue(upRecord, null).ToString();
  30. }
  31. else
  32. {
  33. break;
  34. }
  35. }
  36. }
  37. return treeList.Distinct().ToList();
  38. }
  39. }
  40. }