LINQ Queries with dynamic Order By

前端 未结 3 1797
长发绾君心
长发绾君心 2021-02-14 19:41

I have a query where I need to have ordeby based on a querystring parameter .For example if sortby parameter is price , Query needs to change with price . If its rating than cha

3条回答
  •  醉酒成梦
    2021-02-14 20:36

    If you know exactly which are all the posible parameters that can be used to order, the Jon´s answer is the best one. But if you have an unknown number of parameters you can build the expression dynamically. e.g:

    class Program
    {
        static void Main(string[] args)
        {
            var people = new[]{
                new Person { Name = "David", Age = 40 },
                new Person { Name = "Maria", Age = 12 },
                new Person { Name = "Lucas", Age = 45 }
            }.AsQueryable();
    
            foreach (var p in people.OrderBy("Age"))
            {
                Console.Write(p.Name);
            }
        }
    
        class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
    
    static class IQueryableExtensions
    {
        public static IQueryable OrderBy(this IQueryable items, string propertyName)
        {
            var typeOfT = typeof(T);
            var parameter = Expression.Parameter(typeOfT, "parameter");
            var propertyType = typeOfT.GetProperty(propertyName).PropertyType;
            var propertyAccess = Expression.PropertyOrField(parameter, propertyName);
            var orderExpression = Expression.Lambda(propertyAccess, parameter);
    
            var expression = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { typeOfT, propertyType }, items.Expression, Expression.Quote(orderExpression));
            return items.Provider.CreateQuery(expression);
        }        
    }
    

提交回复
热议问题