In my case my client application is an Angular project which sends the ColumnName (Attribute-Name) as string and the SortOrder as int (-1 DESC, 1 ASC).
With the following extension function its possible to directly Order on an IQueryable based on the Attribute Name and the SortOrder (Could easily be changed to a string).
public static IOrderedQueryable<TSource> ApplyOrderDirection<TSource>(this IQueryable<TSource> source, string attributeName, int sortOrder)
{
if (String.IsNullOrEmpty(attributeName))
{
return source as IOrderedQueryable<TSource>;
}
var propertyInfo = typeof(TSource).GetProperty(attributeName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo == null)
{
throw new ArgumentException("ApplyOrderDirection: The associated Attribute to the given AttributeName could not be resolved", attributeName);
}
Expression<Func<TSource, object>> orderExpression = x => propertyInfo.GetValue(x, null);
if (sortOrder > 0)
{
return source.OrderBy(orderExpression);
}
else
{
return source.OrderByDescending(orderExpression);
}
}
It took me a while to get it work and even to find/build this solution. I hope it can help someone else and save some time.