I am building a repository and would like to be able to pass a list of sorts to a function to receive the entities back in the correct order and possibly paged.
I found out that linq will correctly sort if you use reverse the list of sorts and use Orderby for each sort expression..
foreach (var s in sorts.Reverse())
{
query = query.OrderBy(s);
}
However while testing the addition of the sort direction I found that it only takes the first sort direction and seems to apply that direction on each sort.
private void applySorts(ref IQueryable<TEntity> query, Dictionary<Expression<Func<TEntity, dynamic>>, string> sorts)
{
if (sorts != null)
{
foreach (var s in sorts.Reverse())
{
Expression<Func<TEntity, dynamic>> expr = s.Key;
string dir = s.Value;
if (dir == "d")
{
query = query.OrderByDescending(expr);
}
else
{
query = query.OrderBy(expr);
}
}
}
}
I originally tried to use OrderBy on the first sort and then switch to ThenBy, but this is not possible because ThenBy requires a type of IOrderedQueryable.
I would like to note the use of dictionary may not be the best, if you have any better ideas please share. However, I just wanted to get it running and see how things go.
I am using C#, Linq, and Entity Framework.
Thanks in advance for your time.
Update: Unfortunately I have found that this does not support sorting numbers. Error(Unable to cast the type 'System.Int32' to type 'System.Object'.)