IQueryable不允许ThenBy

时间:2018-05-04 20:28:22

标签: c# asp.net-mvc linq sorting

我尝试按多列对IQueryable进行排序,许多StackOverflow答案似乎表明我应该能够为主要排序执行OrderBy,然后使用ThenBy进行其他排序。 OrderBy很好,但它不允许我使用ThenBy。它没有编译。我不明白为什么......

IQueryable<vMyView> contacts = db.vMyView;

var orderExpressions = new Dictionary<string, Expression<Func<vCRMAllContact, object>>>()
    {
         {"LastName", x => x.LastName},
         {"FirstName", x => x.FirstName},
         {"Email", x => x.Email},
         {"Telephone1", x => x.Telephone1}
     };

contacts = contacts.OrderBy(orderExpressions[sortExpression], ascending).ThenBy(orderExpressions["FirstName"]).Skip(pageIndex * pageSize).Take(pageSize);

1 个答案:

答案 0 :(得分:1)

你的第一个例子是正确的,绝对应该有效:

var contacts = db.vMyView.OrderBy(c => c.LastName).ThenBy(c => c.FirstName);
// not sure why you need to reorder. Which could distort previous sorting
contacts = contacts.OrderBy(orderExpressions[sortExpression]).ThenBy(orderExpressions["FirstName"]);

在第二个例子中看起来有些东西。 OrderByThenBy已经提升,不需要额外的参数。下降的替代方法有适当的后缀:OrderByDescendingThenByDescending