14

Possible Duplicate:
Dynamic LINQ OrderBy

  switch (sort) {
                case "Title":
                    queryResults = queryResults.OrderBy(r => r.Title);
                    break;
                default:
                    queryResults = queryResults.OrderBy(r => r.LastName);
                    break;

Is there any way I can get rid of the switch block above?

Can I do some thing like:

queryResults = queryResults.OrderBy(r => r."sort");
or
queryResults = queryResults.OrderBy(r => r.sort);
Community
  • 1
  • 1
Kuttan Sujith
  • 7,889
  • 18
  • 64
  • 95
  • You'll find your answer in this question: http://stackoverflow.com/questions/41244/dynamic-linq-orderby – web_bod May 22 '12 at 12:42
  • The solutions provided won't work for most linq providers, please see my solution: http://stackoverflow.com/a/21936366/775114 – Mark Powell Feb 21 '14 at 13:59

3 Answers3

8

If you wanted to do this completely dynamic, you could use some reflection (simple example):

string prop = "Title";
var q = queryResults.OrderBy(x => x.GetType().GetProperty(prop).GetValue(x, null));

I wouldn't consider this the nicest solution in any case though. Whether this really makes sense for you depends on where you get the property name from (if you get it from reflection, too, or not) and how many properties there are.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
5

This should do it

queryResults = queryResults.OrderBy(r => sort == "Title" ? r.Title : r.LastName)
Jan Aagaard
  • 10,940
  • 8
  • 45
  • 80
4

You could use DynamcLinq. I haven't touched it in over a year, but I had the expected results. Your code would change to:

queryResults = queryResults.OrderBy(sort);

Oh cool, it's also a NuGet package too

Marc
  • 9,254
  • 2
  • 29
  • 31