0

I have code similar to this in my controller which is working successfully, var results = from c in dbContext.MyClass orderby c.EnrtyDate descending select c; return View(results.ToList());

Now the user would like to select the field(s) to OrderBy. I have 5 dropdown lists each of which contains the same 5 field name choices. The user can select the first field to order by from the first dropdown list, then the second from the second dropdown list, etc. up to a total of five fields; let's call the value of the first selection sort1, the second sort2, then sort3, sort4, and sort5.

I need to make the orderby reflect the choices the user has made, e.g., orderby sort1, sort2, sort3, sort4, sort5 How do I reference this fields in the orderby since they are variables containing the field names, not the actual field names themselves? I cannot code for all of the hundreds of possible combinations individually.

  • It usually helps to include a short example of what you're working with so that users can easily help. Keep that in mind for future questions (or to consider improving this one). – leigero Jan 28 '15 at 16:23
  • maybe this answer could help to you http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet – Alexey Jan 28 '15 at 16:43

1 Answers1

0

You can nest order bys. You call the OrderBy for the main sort if you are sorting in an ascending manner and OrderByDescending if you are sorting in a descending manner. The nested sort, for sort two has to use ThenBy if it is ascending or ThenByDescending if it is descending. Basically, ThenBy and ThenByDescending will do exactly what you wanted.

Read more here and here.

Community
  • 1
  • 1
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175