使用Linq动态排序

Linq排序很方便,如果能动态创建Expression再排序就更方便了。

  1. 正序还是倒序排列

    var order = typeof(Enumerable).GetMember(direction == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending")
                    .First() as MethodInfo;
    order = order.MakeGenericMethod(typeof(T), typeof(TKey));
  2. 创建表达式

    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();
  3. 执行

    var result = order.Invoke(null, new object[] { source, @delegate });
    

posted on 2015-03-12 10:35  beastplus  阅读(435)  评论(0编辑  收藏  举报

导航