只为成功找方向,不为失败找借口

每天都不能停止前进的脚步
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Lambda动态排序

Posted on 2017-10-19 10:49  冰碟  阅读(707)  评论(0编辑  收藏  举报
private static IList<T> IListOrderBy<T>(IList<T> list, string propertyName) where T : new()
        {
            if (list == null || list.Count == 0)
            {
                return list;
            }

            Type elementType = Queryable.AsQueryable(list).ElementType;
            //PropertyInfo propertyInfo = elementType.GetProperty(propertyName);
            ParameterExpression parameter = Expression.Parameter(elementType, "");
            Expression body = Expression.PropertyOrField(parameter, propertyName);

            Expression sourceExpression = list.AsQueryable().Expression;

            //Type sourcePropertyType = propertyInfo.PropertyType;
            var selector = Expression.Lambda(body, parameter);

            Expression lambda = Expression.Call(typeof(Queryable), "OrderBy", new Type[]
            {
                elementType,
                selector.Body.Type
            }, sourceExpression, selector);

            //Expression lambda = Expression.Call(typeof(Queryable), "OrderBy", new Type[]
            //{
            //    elementType,
            //    sourcePropertyType
            //}, sourceExpression, Expression.Lambda(body, parameter));
       var query = list.AsQueryable().Provider.CreateQuery<T>(lambda);
       return query.ToList<T>(); }