首页新闻找找看学习计划

Lambda OrderBy问题

0
悬赏园豆:5 [已解决问题] 解决于 2019-09-21 10:10

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;
}

QT2019的主页 QT2019 | 初学一级 | 园豆:77
提问于:2019-09-21 08:42
< >
分享
最佳答案
1

网上找的动态排序,使用扩展方法
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);
    }

}
收获园豆:5
geass.. | 小虾三级 |园豆:1737 | 2019-09-21 09:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册