首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何动态指定Linq OrderBy参数?

如何动态指定Linq OrderBy参数?
EN

Stack Overflow用户
提问于 2011-09-01 09:10:21
回答 8查看 100.2K关注 0票数 102

如何使用作为参数的值指定传递给orderby的参数?

例如:

代码语言:javascript
复制
List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}

目前正在实施:

代码语言:javascript
复制
List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();

我怎么才能把它作为参数而不是c.Address呢?

示例

代码语言:javascript
复制
 string param = "City";
 List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-09-01 09:54:50

这里有一种使用反射的可能性。

代码语言:javascript
复制
var param = "Address";    
var propertyInfo = typeof(Student).GetProperty(param);    
var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));
票数 140
EN

Stack Overflow用户

发布于 2011-09-01 09:46:51

您可以使用一点反射来构建表达式树,如下所示(这是一个扩展方法):

代码语言:javascript
复制
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty,
                          bool desc) 
{
     string command = desc ? "OrderByDescending" : "OrderBy";
     var type = typeof(TEntity);
     var property = type.GetProperty(orderByProperty);
     var parameter = Expression.Parameter(type, "p");
     var propertyAccess = Expression.MakeMemberAccess(parameter, property);
     var orderByExpression = Expression.Lambda(propertyAccess, parameter);
     var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
                                   source.Expression, Expression.Quote(orderByExpression));
     return source.Provider.CreateQuery<TEntity>(resultExpression);
}

orderByProperty是要作为排序依据的属性名称,如果将true作为desc的参数传递,则将按降序排序;否则,将按升序排序。

现在,您应该能够执行existingStudents.OrderBy("City",true);existingStudents.OrderBy("City",false);

票数 143
EN

Stack Overflow用户

发布于 2017-12-07 21:04:48

answer by @Icarus上展开:如果您希望扩展方法的返回类型是IOrderedQueryable而不是IQueryable,您可以简单地将结果转换为以下内容:

代码语言:javascript
复制
public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc)
{
    string command = desc ? "OrderByDescending" : "OrderBy";
    var type = typeof(TEntity);
    var property = type.GetProperty(orderByProperty);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExpression = Expression.Lambda(propertyAccess, parameter);
    var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
        source.Expression, Expression.Quote(orderByExpression));
    return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7265186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档