You can use the OrderByString extension. https://www.nuget.org/packages/OrderByString/ It takes to string collation. Lines of sorting options can be separated by comma-based lists of property names, such as "Prop1, Prop2", or may contain sorting order, as in "Prop1 DESC, Prop2 ASC".
using OrderByExtensions; public static IQueryable<T> OrderData<T>(IQueryable<T> data) { try { Order order = Order.ASC; var result = Enum.TryParse<Order>(_gridSettings.SortOrder, true, out order); var sortColumn = _gridSettings.IsSearch ? _gridSettings.SortColumn : _defaultColumn; data = data.OrderBy(sortColumn + " " + _gridSettings.SortOrder.ToString()); } catch (Exception ex) { log.WriteLog(MethodBase.GetCurrentMethod(), LogLevel.FATAL, ex); } return data; }
OR
You can use the following GetExpressionForProperty method, which returns the expected sort expression for OrderBy, OrderByDescending, ThenBy, or ThenByDescending.
private static IQueryable<T> ExpressionSort<T>(Order order, IQueryable<T> data, PropertyInfo property) { Expression<Func<T, object>> propertyExpression = GetExpressionForProperty<T>(property); return order == Order.DESC ? data.OrderByDescending(propertyExpression) : data.OrderBy(propertyExpression); } static Expression<Func<TSource, object>> GetExpressionForProperty<TSource>(PropertyInfo propertyInfo) { var param = Expression.Parameter(typeof(TSource)); return Expression.Lambda<Func<TSource, object>>( Expression.Convert( Expression.Property(param, propertyInfo), typeof(object) ) , param); }
Grax source share