Phantom Phantom - 1 year ago 212
C# Question

Dynamic LINQ - AsQueryable 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
.OrderBy(sortCol + " " + sortDir, sortSecCol + " " + sortSecDir)
.Skip((page - 1) * rowsPerPage)
.Select(o => new Orders

What I am trying to do in here is I want the column
be the secondary sort whenever it is not a primary sort. But it didn't work when I selected other column as a primary sort. In order words, when other column is select as primary sort in descending order,
should also be in descending order, I am what did I missed in my code. The
method I used is come from here.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download