使用Linq动态排序
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 });