【转】Linq初体验——Order By 通过属性名动态排序

当前项目要求能对表格的所有列进行排序。而我对linq掌握程度使我仅仅能写出下面这样的代码:

case SortFields.Price:

    if (rules == SortRules.ESC)

    {

        result = result.OrderBy(s => s.Price);

    }

    else

    {

        result = result.OrderByDescending(s => s.Price);

    }

    break;

case SortFields.BuyDate:

    if (rules == SortRules.ESC)

    {

        result = result.OrderBy(s => s.BuyDate);

    }

    else

    {

        result = result.OrderByDescending(s => s.BuyDate);

    }

    break;

这让我十分郁闷,写枚举,写switch,,虽然写法很简单,但用这样的写法对每个字段进行排序的话,我将面临严重的体力活。

我想到了ADO的SQL字符串拼接,此时的排序要求变的很轻松。

那么作为新生事物的linq,ADO能轻松做到的事,没理由做不到。

顺着这样的思路,在Google上一番搜索。

在下面的文章中看到了希望:

http://www.cnblogs.com/126/archive/2007/09/09/887723.html

借鉴文章中的代码,几番尝试,终于有点眉目,传个字段名字符串和类型进行排序。。。

最后在下面的文章中直接找到了现成的(Orz):

http://hi.baidu.com/snake1964/blog/item/0b68d42ac1d4c120d52af149.html

照着上文的代码,简化了一下

public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string propertyStr) where TEntity : class

{

    ParameterExpression param = Expression.Parameter(typeof(TEntity), "c");

    PropertyInfo property = typeof(TEntity).GetProperty(propertyStr);

    Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);

    LambdaExpression le = Expression.Lambda(propertyAccessExpression, param);

    Type type = typeof(TEntity);

    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(le));

    return source.Provider.CreateQuery<TEntity>(resultExp);

}

反射+System.Linq.Expressions下的几个函数动态生成lambda表达式。

posted @ 2012-11-19 14:12  第八颗流星  阅读(431)  评论(0编辑  收藏  举报