i have api get
method accepts sort property string. best solution handle without using switch
statement?
public actionresult index(string sortorder) { var students = s in db.students select s; switch (sortorder) { case "lastname": students = students.orderbydescending(s => s.lastname); break; case "enrollmentdate": students = students.orderby(s => s.enrollmentdate); break; case "birthday": students = students.orderby(s => s.birthday); break; default: students = students.orderby(s => s.lastname); break; } return view(students.tolist()); }
following code found on microsoft's page, believe there should more elegant way it.
use following method achieve flexible sorting. method requires property name , sorting direction parameters.
public func<iqueryable<t>, iorderedqueryable<t>> getorderbyexpression<t>(string propertyname, bool isdescending = false) { type typequeryable = typeof(iqueryable<t>); parameterexpression argqueryable = system.linq.expressions.expression.parameter(typequeryable, "p"); var outerexpression = system.linq.expressions.expression.lambda(argqueryable, argqueryable); var entitytype = typeof(t); parameterexpression arg = system.linq.expressions.expression.parameter(entitytype, "x"); expression expression = arg; propertyinfo propertyinfo = entitytype.getproperty(propertyname, bindingflags.ignorecase | bindingflags.public | bindingflags.instance); expression = system.linq.expressions.expression.property(expression, propertyinfo); lambdaexpression lambda = system.linq.expressions.expression.lambda(expression, arg); string methodname = isdescending ? "orderbydescending" : "orderby"; methodcallexpression resultexp = system.linq.expressions.expression.call(typeof(queryable), methodname, new type[] { typeof(t), entitytype }, outerexpression.body, system.linq.expressions.expression.quote(lambda)); var finallambda = system.linq.expressions.expression.lambda(resultexp, argqueryable); return (func<iqueryable<t>, iorderedqueryable<t>>)finallambda.compile(); }
usage:
iqueryable<student> query = db.set<student>(); var orderby = getorderbyexpression<student>(sortorder, true); if(orderby != null){ query = orderby(query); }
Comments
Post a Comment