c# - Dynamically Sort by lambda expression -
i m doing sorting in application shown below .
public iqueryable<users> selectall(string ssortexpression, string ssortorder) { if (ssortorder == "asc") { switch (ssortexpression) { case "firstname": return usersrepository.entities.orderby(x => x.firstname); case "lastname": return usersrepository.entities.orderby(x => x.lastname); default: return usersrepository.entities.orderby(x => x.id); } } else { switch (ssortexpression) { case "firstname": return usersrepository.entities.orderbydescending(x => x.firstname); case "lastname": return usersrepository.entities.orderbydescending(x => x.lastname); default: return usersrepository.entities.orderbydescending(x => x.username); } } }
its fine , have sort on fields in users
table (around 30 fields ) . method big
i tried using reflections this
public iqueryable<users> selectall(string ssortexpression, string ssortorder) { var _property = usersrepository.gettype().getproperties().where(a => a.name == ssortexpression); if (ssortorder == "asc") { return usersrepository.entities.orderby(x => _property); } else { return usersrepository.entities.orderbydescending(x => _property); } }
but faild.
is there better way ? in advance
the easiest way go: change method accept expression
instead of string
:
public iqueryable<users> selectall<tprop>(expression<func<users, tprop>> selector, string ssortorder) { if (ssortorder == "asc") { return usersrepository.entities.orderby(selector); } else { return usersrepository.entities.orderbydescending(selector); } }
you can call as:
selectall(x => x.lastname, "asc");
or if need string, have generate expression tree using system.linq.expressions.expression
class method:
public iqueryable<users> selectall<tprop>(string ssortexpression, string ssortorder) { var param = expression.parameter(typeof(users)); var propexpression = expression.lambda<func<users, tprop>>(expression.property(param, ssortexpression), param); if (ssortorder == "asc") { return usersrepository.entities.orderby(propexpression); } else { return usersrepository.entities.orderbydescending(propexpression); } }
but require specify generic type parameter on selectall
call:
var results = selectall<int>("id", "asc");
Comments
Post a Comment