I have an IQueryable query and you want to dynamically apply its sort, sorting can be on many columns (asc or desc). I wrote the following general function:
private IQueryable<T> ApplySorting<T,U>(IQueryable<T> query, Expression<Func<T, U>> predicate, SortOrder order)
{
if (order == SortOrder.Ascending)
{
{
return query.OrderBy<T, U>(predicate);
}
}
else
{
{
return query.OrderByDescending<T, U>(predicate);
}
}
}
SortOrder is my simple enumeration with two values: Ascending and Descending
Then I call this function in a loop, for each column that the user requested sorting. However, I noticed that it fails because it is always sorted by the last column used, ignoring the others.
Then I found there the "ThenBy" method in IOrderedQueryable, so a valid use:
var q = db.MyType.OrderBy(x=>x.Col1).ThenBy(y=>y.Col2);
But how can I make it common? I tried to check if the query is IOrderedQueryable, but it seems to always be true, even if it is simple. Var q = from x in db.MyType select x
, . :
var q = db.MyType.OrderBy(x=>x.Col1).OrderBy(y=>y.Col2);