Linq排序很方便,如果能动态创建Expression再排序就更方便了。
- 正序还是倒序排列
var order = typeof(Enumerable).GetMember(direction == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending") .First() as MethodInfo;order = order.MakeGenericMethod(typeof(T), typeof(TKey));
- 创建表达式
var entityParam = Expression.Parameter(typeof(T), "item");Expression columnExpr = Expression.Property(entityParam, TKeyPropertyInfo);var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), TKeyPropertyType);//属性返回值类型var @delegate = Expression.Lambda(delegateType, columnExpr, entityParam).Compile();
- 执行
var result = order.Invoke(null, new object[] { source, @delegate });
时间: 2024-10-11 12:58:02