string sort ="Age":
string order="asc";
List<Person> persons = new List<Person>
{
new Person{ Name="张三",Age=19,Score=99 },
new Person{ Name="李四",Age=17,Score=69 },
new Person{ Name="王五",Age=20,Score=79 }
};
switch(order)
{
case "asc":
//这样不启动排序,如果p.Age这样就可以,请问一下,为什么不能这样指定,需要如何解决
persons = person.OrderBy(p => sort).ToList();
break;
}
网上找的动态排序,使用扩展方法
var q = persons.AsQueryable().OrderBy("Age", true);
public static class Test
{
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string propertyName,bool asc = true) where TEntity : class
{
string command = asc ? "OrderBy" : "OrderByDescending";
var type = typeof(TEntity);
var property = type.GetProperty(propertyName);
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);
}
}