4

Possible Duplicate:
LINQ: orderby with dynamic string parameter

i'm sorting a IEnumarable with an OrderBy() clause. I'v a list with string with a value which contains the field I wanna order by. Now I'm using a switch statement for each property name.

  swich (propertyname)
    case "name":
      list = list.OrderBy(l=>l.name).ToList();
      break;
    case "property":
      list = list.OrderBy(l=>l.property).ToList();
      .....

is there a simple solution to use the string "propertyname" as an attribute in the orderby clause?

As I've done it I get an solution that is far from desirable. Not only is it more work to code each property, but if in the future any attribute is added this update wil be forgotten in the function i'm writing.

hope someone has got a better solution.

Community
  • 1
  • 1
Luuk Krijnen
  • 1,180
  • 3
  • 14
  • 37

2 Answers2

3
var list = new List<MyClass>();

// Gets an object to give us access to the property with the given name of type MyClass
var propertyInfo = typeof(MyClass).GetProperty(propertyName);

// Each item is ordered by the value of the property
list = list.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();

Explaining predicate:

var xPropVal = propertyInfo.GetValue(x, null);

Using the property info object, you get the value of the object x, with null parameters. The parameters will be used for indexers, in this case, since this is a property info object.

But since the properties in this case are all simple properties, the second parameter should be null or an empty object array.

SimpleVar
  • 14,044
  • 4
  • 38
  • 60
1

The easiest way to do this is to look at he Dynamic Linq sample provided by Microsoft. Scott Guthrie has a blog post about it here: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

The you can simply do this:

string propertyname = ...
list.OrderBy(propertyname).ToList();
samjudson
  • 56,243
  • 7
  • 59
  • 69