zoukankan      html  css  js  c++  java
  • 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表达式。

  • 相关阅读:
    Day 69
    Day 68
    Day 67
    Day 66
    Day 65
    Day 64
    Day 63
    Day 62
    Day 61
    Day 60
  • 原文地址:https://www.cnblogs.com/xxfss2/p/1905023.html
Copyright © 2011-2022 走看看