Skip to content

Instantly share code, notes, and snippets.

@dataneek
Created February 26, 2016 22:27
Show Gist options
  • Save dataneek/e74670e519fdf203503f to your computer and use it in GitHub Desktop.
Save dataneek/e74670e519fdf203503f to your computer and use it in GitHub Desktop.
public static class SortQueryableExtensions
{
public static IQueryable<T> ApplySort<T>(this IQueryable<T> queryable, string sort)
{
if (queryable == null)
throw new ArgumentNullException();
if (string.IsNullOrWhiteSpace(sort))
return queryable;
string completeSortExpression = "";
foreach (var sortOption in sort.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
if (sortOption.StartsWith("-"))
{
completeSortExpression += sortOption.Remove(0, 1) + " descending,";
}
else
{
completeSortExpression += sortOption + ",";
}
}
if (!string.IsNullOrWhiteSpace(completeSortExpression))
{
queryable =
queryable
.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
}
return queryable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment