Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a list based on a user's selections in ASP.NET MVC?

I have a list of customers that can be sorted by anywhere from 1 to 6 fields based on a user's selection. The sort fields can be in any order. If I know the fields and the sequence ahead of time, sorting is easy:

customers = customers
                .OrderBy(c => c.LastName)
                .ThenBy(c => c.City)
                .ThenBy(c => c.Age).ToList();

How would I pass in the sort fields at runtime? Is there a way to do something like this?

    string sortField1 = "State";
    string sortField2 = "City";
    string sortField3 = "Type";

    customers = customers
                .OrderBy(c => c.sortField1)
                .ThenBy(c => c.sortField2)
                .ThenBy(c => c.sortField3).ToList();
like image 217
Jon Crowell Avatar asked Nov 05 '22 08:11

Jon Crowell


1 Answers

Have a look at http://tomasp.net/articles/dynamic-linq-queries.aspx for a tutorial on how to build Dynamic LinQ queries at runtime. This should be what you are looking for.

like image 169
ChrisiPK Avatar answered Nov 15 '22 07:11

ChrisiPK