|
12345678910111213141516171819202122232425262728293031323334 |
- using System.Linq.Expressions;
- using HealthMonitor.Util.QueryObjects;
-
- namespace HealthMonitor.Core.Query.Extensions
- {
- public static class OrderConditionsExt
- {
- public static IQueryable<T> OrderConditions<T>(this IQueryable<T> query, IEnumerable<OrderByCondition> conditions)
- {
- if (conditions == null) return query;
-
- foreach (var orderinfo in conditions)
- {
- try
- {
- var parameter = Expression.Parameter(typeof(T));
- Expression propertySelector = Expression.Property(parameter, orderinfo.Key!);
-
- //需要用Expression.Convert转换为object表达式,不然值类型的排序会报错
- var orderby = Expression.Lambda<Func<T, object>>(Expression.Convert(propertySelector, typeof(object)), parameter);
- if (orderinfo.IsDesc)
- query = query.OrderByDescending(orderby);
- else
- query = query.OrderBy(orderby);
- }
- catch (Exception)
- {
- continue;
- }
- }
- return query;
- }
- }
- }
|