What you basically want to do here is build the LINQ query dynamically. To do this, you need to modify / build the expression tree at run time. If you are not familiar with expression trees and type Expression<T>, I recommend this article and the link pages in the See Also section:
http://msdn.microsoft.com/en-us/library/bb397951.aspx
, , . IQueryable<T>, , , LINQ, ( , , ). , , ( /):
public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> query, string sortColumn, bool descending)
{
var parameter = Expression.Parameter(typeof(T), "p");
string command = "OrderBy";
if (descending)
{
command = "OrderByDescending";
}
Expression resultExpression = null;
var property = typeof(T).GetProperty(sortColumn);
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { typeof(T), property.PropertyType },
query.Expression, Expression.Quote(orderByExpression));
return query.Provider.CreateQuery<T>(resultExpression);
}
, Name ascending :
dataSet.OrderByDynamic("Name", false)
. , .
share