Reputation: 2746
I'm trying to sort an IQueryable by multiple columns and many StackOverflow answers seem to indicate I should be able to do an OrderBy for the Primary sort and then a ThenBy for additional sorts. The OrderBy is fine but it's not allowing me to use ThenBy. It doesn't compile. I don't get why...
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);
Upvotes: 3
Views: 1225
Reputation: 5858
Your first example is correct and absolutely should work:
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"]);
Something looks off in your second example. OrderBy
and ThenBy
are already ascending there's no need for the additional parameter. There are alternatives for descending which are suffixed appropriately: OrderByDescending
and ThenByDescending
.
Upvotes: 1