如何使用作为参数的值指定传递给orderby
的参数?
例如:
List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}
目前正在实施:
List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();
我怎么才能把它作为参数而不是c.Address
呢?
示例
string param = "City";
List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();
发布于 2011-09-01 09:54:50
这里有一种使用反射的可能性。
var param = "Address";
var propertyInfo = typeof(Student).GetProperty(param);
var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));
发布于 2011-09-01 09:46:51
您可以使用一点反射来构建表达式树,如下所示(这是一个扩展方法):
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);
了
发布于 2017-12-07 21:04:48
在answer by @Icarus上展开:如果您希望扩展方法的返回类型是IOrderedQueryable而不是IQueryable,您可以简单地将结果转换为以下内容:
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);
}
https://stackoverflow.com/questions/7265186
复制相似问题