Orderby 不工作

Orderby not working

我正在使用动态排序根据多个条件进行排序,这是我的代码:

    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  
                {

我想在这里做的是,我希望列 OrderID 成为次要排序,只要它不是主要排序,但当我实际 selected 时它不起作用其他列作为主要排序。

换句话说,当其他列以 select 作为主要降序排序时, OrderID 也应该按降序排列,我不确定我的代码中遗漏了什么。

我使用的OrderBy方法来自here (MSDN).

您使用的方法具有以下签名:

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

所以 sortSecCol + " " + sortSecDir 转到 values 参数,而整个排序应该在 ordering 参数中作为逗号分隔列表提供。

您可以改用这样的东西:

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

试试这个:

    if (sortCol == "OrderID" && sortDir == "ASC")
    {
        _res = l.OrderBy(x => x.OrderId).ThenBy(x => x.AnotherField);
    }
    if (sortCol == "OrderID" && sortDir == "DESC")
    {
        _res = l.OrderByDescending(x => x.OrderId).ThenByDescending(x => x.AnotherField);
    }
    if (sortCol == "AnotherField" && sortDir == "ASC")
    {
        _res = l.OrderBy(x => x.AnotherField).ThenBy(x => x.OrderId);
    }
    if (sortCol == "AnotherField" && sortDir == "DESC")
    {
        _res = l.OrderByDescending(x => x.AnotherField).ThenByDescending(x => x.OrderId);
    }

    _res.Skip((page - 1) * rowsPerPage)
            .Take(rowsPerPage)
            .Select(o => new Orders  
            {