c# - Dynamic Order By in Linq -
i have app accesses database , has order results different fields depending on input.
here function sorting:
iqueryable<entity> getsorteddata(iqueryable<entity> result, string orderby, bool desc) { switch (orderby.tolower()) { case "id": result = result.orderby(c => c.id); break; case "code": result = result.orderby(c => c.code); break; case "active": result = result.orderby(c => c.active); break; default: result = result.orderby(c => c.name); break; } if (pagedata.sortdesc) { var res = result.tolist(); res.reverse(); return res.asqueryable(); } return result; }
there problems code don't like:
too repetitive code. if "pure
sql
" query, likeselect * data_table order case @orderby when 'id' id when 'code' code
when 'active' active else name
end ;conversion list , reversing. can not change return type , not want write more useless code (essentially doubling
switch
case
orderbydescending
).
can suggest ways of making function better-looking, preferably still using linq
?
well, definitely want use orderbydescending
instead of reversing. it's not going quite brief sql, @ least use:
iqueryable<entity> getsorteddata(iqueryable<entity> result, string orderby, bool desc) { switch (orderby.tolowerinvariant()) { case "id": return desc ? result.orderbydescending(c => c.id) : result.orderby(c => c.id); case "code": return desc ? result.orderbydescending(c => c.code) : result.orderby(c => c.code); case "active": return desc ? result.orderbydescending(c => c.active) : result.orderby(c => c.active); default: return desc ? result.orderbydescending(c => c.name) : result.orderby(c => c.name); } }
you remove repetition own extension method:
public static iorderedqueryable<tsource> orderby<tsource, tkey>( iqueryable<tsource> source, expression<func<tsource, tkey>> keyselector, bool descending) => descending ? source.orderbydescending(keyselector) : source.orderby(keyselector);
then write:
iqueryable<entity> getsorteddata(iqueryable<entity> result, string orderby, bool desc) { switch (orderby.tolowerinvariant()) { case "id": return result.orderby(c => c.id, desc); case "code": return result.orderby(c => c.code, desc); case "active": return result.orderby(c => c.active, desc); default: return result.orderby(c => c.name, desc); } }
Comments
Post a Comment