using System.Linq.Expressions; using HealthMonitor.Util.QueryObjects; namespace HealthMonitor.Core.Query.Extensions { public static class OrderConditionsExt { public static IQueryable OrderConditions(this IQueryable query, IEnumerable 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>(Expression.Convert(propertySelector, typeof(object)), parameter); if (orderinfo.IsDesc) query = query.OrderByDescending(orderby); else query = query.OrderBy(orderby); } catch (Exception) { continue; } } return query; } } }