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.

35 lines
1.2KB

  1. using System.Linq.Expressions;
  2. using HealthMonitor.Util.QueryObjects;
  3. namespace HealthMonitor.Core.Query.Extensions
  4. {
  5. public static class OrderConditionsExt
  6. {
  7. public static IQueryable<T> OrderConditions<T>(this IQueryable<T> query, IEnumerable<OrderByCondition> conditions)
  8. {
  9. if (conditions == null) return query;
  10. foreach (var orderinfo in conditions)
  11. {
  12. try
  13. {
  14. var parameter = Expression.Parameter(typeof(T));
  15. Expression propertySelector = Expression.Property(parameter, orderinfo.Key!);
  16. //需要用Expression.Convert转换为object表达式,不然值类型的排序会报错
  17. var orderby = Expression.Lambda<Func<T, object>>(Expression.Convert(propertySelector, typeof(object)), parameter);
  18. if (orderinfo.IsDesc)
  19. query = query.OrderByDescending(orderby);
  20. else
  21. query = query.OrderBy(orderby);
  22. }
  23. catch (Exception)
  24. {
  25. continue;
  26. }
  27. }
  28. return query;
  29. }
  30. }
  31. }