Phantom Phantom - 3 months ago 8
C# Question

Orderby not working

I am sorting on multiple criteria using dynamic sorting, here's my code:

public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sortCol = "OrderID", string sortDir = "ASC", string sortSecCol = "OrderID", string sortSecDir = "ASC")
{
List<Orders> res;

using (var nwd = new NorthwindEntities())
{
var _res = nwd.Orders
.AsQueryable()
.OrderBy(sortCol + " " + sortDir, sortSecCol + " " + sortSecDir)
.Skip((page - 1) * rowsPerPage)
.Take(rowsPerPage)
.Select(o => new Orders
{


What I am trying to do in here is I want the column
OrderID
be the secondary sort whenever it is not a primary sort, but it didn't work when I actually selected other column as a primary sort.

In order words, when other column is select as primary sort in descending order,
OrderID
should also be in descending order, I am not sure what did I missed in my code.

The
OrderBy
method I used is come from here (MSDN).

Answer

The method you are using has the following signature:

public static IQueryable<T> OrderBy<T>(
    this IQueryable<T> source,
    string ordering,
    params object[] values
)

so the sortSecCol + " " + sortSecDir goes to values argument, while the whole ordering is supposed to be provided as comma separated list in the ordering argument.

You can use something like this instead:

var ordering = sortCol + " " + sortDir;
if (sortSecCol != sortCol)
    ordering += ", " + sortSecCol + " " + sortSecDir;
...
   .OrderBy(ordering)
...