I need to set the key in the OrderBy clause using linq , where the key is a property of an object. I only have the property name with me. How can i set the property dynamically.
class Obj
{
string Level
{
get;
set;
}
}
List<Obj> objList;
objList.OrderByDescending(x => x.Level); => "here i only have property name."
Hope any one can help
Thanks
Sunil
You can do this by Extension Methods and Creating Expression Trees dynamically like
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> enumerable, string sortColumn)
{
var param = Expression.Parameter(typeof(T), "x");
var mySortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param);
return enumerable.OrderByDescending(mySortExpression);;
}
and for OrderBy
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> enumerable, string sortColumn)
{
var param = Expression.Parameter(typeof(T), "x");
var mySortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param);
return enumerable.OrderBy(mySortExpression);;
}
and you can combine these two in one like
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> enumerable, string sortColumn, string direction)
{
var param = Expression.Parameter(typeof(T), "x");
var mySortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param);
IOrderedQueryable<T> iQuery;
switch(direction)
{
case "desc":
iQuery = enumerable.OrderByDescending(mySortExpression);
break;
case "asc":
default :
iQuery = enumerable.OrderBy(mySortExpression);
break;
}
return iQuery;
}
Then you can call it like objList.OrderBy("Level","asc")
//For Ascending
objList.OrderBy("Level","desc")
//For Descending
Hope It will help