zoukankan      html  css  js  c++  java
  • 让Linq的OrderBy支持动态字段

     public static class QueryableExtension
        {
            public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string propertyName)
            {
                return _OrderBy<T>(query, propertyName, false);
            }
            public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> query, string propertyName)
            {
                return _OrderBy<T>(query, propertyName, true);
            }
    
            static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName,bool isDesc)
            {
                string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";
    
                var memberProp = typeof(T).GetProperty(propertyName);
    
                var method = typeof(QueryableExtension).GetMethod(methodname)
                                           .MakeGenericMethod(typeof(T), memberProp.PropertyType);
    
                return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp });
            }
            public static IOrderedQueryable<T> OrderByInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty)
            {//public
                return query.OrderBy(_GetLamba<T, TProp>(memberProperty));
            }
            public static IOrderedQueryable<T> OrderByDescendingInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty)
            {//public
                return query.OrderByDescending(_GetLamba<T, TProp>(memberProperty));
            }
            static Expression<Func<T, TProp>> _GetLamba<T, TProp>(PropertyInfo memberProperty)
            {
                if (memberProperty.PropertyType != typeof(TProp)) throw new Exception();
    
                var thisArg = Expression.Parameter(typeof(T));
                var lamba = Expression.Lambda<Func<T, TProp>>(Expression.Property(thisArg, memberProperty), thisArg);
    
                return lamba;
            }
        }
    View Code

    调用:

    IQueryable<User> userQuery = ...;
    //正序
    userQuery = userQuery.OrderBy("Code");
    //降序
    userQuery = userQuery.OrderByDescending("Code");
  • 相关阅读:
    VB.NET中lambda的写法
    C#中DllImport用法和路径问题
    SQL*Loader 和 Data Pump
    批处理-函数定义及应用01
    Office 2010 KMS激活原理和案例分享
    Hyper-V架构与VMware ESXi的差异
    Tomcat免安装配置2
    Tomcat免安装配置
    域名解析过程
    内部类访问的局部变量必须加final
  • 原文地址:https://www.cnblogs.com/dot-caohui/p/10968861.html
Copyright © 2011-2022 走看看