c# - Order a list by a property name(string value)? -
i have list of object
s. how can order list using property name?
string orderbyfield = "code"; list<object> l = filllist(); l = l.orderby(o => orderbyfield);
can have extension problem?
if don't have provide property name string, it's pretty simple using dynamic
:
list<object> l = filllist(); l = l.orderby(o => ((dynamic)o).id);
if property name has string, gets more bit complicated can done using reflection (although not efficient):
l = l.orderby(o => o.gettype() .getproperty("code") .getvalue(o, null));
you should think adding error handling, e.g. if property doesn't exist.
also, if elements in list have same runtime type, much more efficient compile getter function using look trees , reusing (instead of straight using reflection).
public static func<object, object> creategetter(type runtimetype, string propertyname) { var propertyinfo = runtimetype.getproperty(propertyname); // create parameter (object obj) var obj = expression.parameter(typeof(object), "obj"); // cast obj runtimetype var objt = expression.typeas(obj, runtimetype); // property accessor var property = expression.property(objt, propertyinfo); var convert = expression.typeas(property, typeof(object)); homecoming (func<object, object>)expression.lambda(convert, obj).compile(); }
and utilize like:
var codegetter = creategetter(l[0].gettype(), "code"); // using 1st element illustration l = l.orderby(o => codegetter(o));
c# linq
No comments:
Post a Comment