Using string as attribute for linq query

Possible duplicate:
LINQ: orderby with dynamic string parameter

I sort IEnumarable with an OrderBy () clause. I'v a list with a string with a value that contains the field that I want to order. Now I use the 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 an orderby clause?

As I did, I get a solution that is far from what I want. Not only does this work more for encoding each property, but if any attribute is added in the future, this update will be forgotten in the function I'm writing.

hope someone has a better solution.

+3
source share
2
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();

:

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

, x . , , .

, .

+2

- Dynamic Linq, Microsoft. : http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

:

string propertyname = ...
list.OrderBy(propertyname).ToList();
+1

All Articles