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