Hello
After searching online and going through past stackoverflow posts for a suitable implementation for dynamic ordering with linq, i came up with my own implementation that borrows a few things from other solutions i have previously seen.
What i need to know is if this implementation is threadsafe? I don't believe it is as i am passing an enumerable generic type object (reference type) as a parameter into the static method but i would like to know if i am missing anything else and hopefully how to make it completely threadsafe.
public class OrderByHelper
{
public static IEnumerable<T> OrderBy<T>(IQueryable<T> items, string sortColumn, string sortDirection, int pageNumber, int pageSize)
{
Type t = typeof(T).GetProperty(sortColumn).PropertyType;
return (IEnumerable<T>)(typeof(OrderByHelper)
.GetMethod("OrderByKnownType")
.MakeGenericMethod(new[] { typeof(T), t })
.Invoke(null, new object[] { items, sortColumn, sortDirection, pageNumber, pageSize }));
}
public static IEnumerable<K> OrderByKnownType<K, T>(IQueryable<K> items, string sortColumn, string sortDirection, int pageNumber, int pageSize)
{
var param = Expression.Parameter(typeof(K), "i");
var mySortExpression = Expression.Lambda<Func<K, T>>(Expression.Property(param, sortColumn), param);
if (!string.IsNullOrEmpty(sortDirection))
{
if (sortDirection == "ASC")
return items.OrderBy(mySortExpression).Skip((pageNumber - 1) * pageSize).Take(pageSize);
else
return items.OrderByDescending(mySortExpression).Skip((pageNumber - 1) * pageSize).Take(pageSize);
}
else
throw new InvalidOperationException("No sorting direction specified.");
}
}