I have a grid on a page which I want to be sortable on multiple columns at the same time.
For example:
UserID FirstName LastName
=======================================
1 Bruce Wayne
2 Peter Parker
3 Clark Kent
4 Tony Stark
5 Helena Wayne
The user can choose to order by LastName ASC then by FirstName DESC, which would produce the following:
UserID FirstName LastName
=======================================
3 Clark Kent
2 Peter Parker
4 Tony Stark
5 Helena Wayne
1 Bruce Wayne
The user could reset the ordering and decide to order it in some other fashion.
How can I achieve this in LINQ? As far as I know, the way to chain ordering is to do something like
superheroes.OrderBy(x => x.LastName).ThenByDescending(x => x.FirstName)
Obviously, I don’t want to have to write out every possible combination of column orders (my grid may have up to 10 columns). Is there some way to make the ordering sequence dynamic?
You need to use dynamic LINQ. Have a look at Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)