c# - How to Check conditions in Order By clause using LINQ? -
can me check value parameter in order clause.
my code below.
public list<tablename> functionname(keyvalue){ return mylist.orderby(keyvalue=="name"?x=>x.name:x=>x.college); }
please me. thank you.
most appropriate way make orderby(parametername)
method accept name of parameter want order by. can write own extension method or use this extension method. using extension method must located in static class.
public static class extensionmethods { public static ienumerable<t> orderby<t>(this ienumerable<t> list, string sortexpression) { sortexpression += ""; string[] parts = sortexpression.split(' '); bool descending = false; string property = ""; if (parts.length > 0 && parts[0] != "") { property = parts[0]; if (parts.length > 1) { descending = parts[1].tolower().contains("esc"); } propertyinfo prop = typeof(t).getproperty(property); if (prop == null) { throw new exception("no property '" + property + "' in + " + typeof(t).name + "'"); } if (descending) return list.orderbydescending(x => prop.getvalue(x, null)); else return list.orderby(x => prop.getvalue(x, null)); } return list; } }
and then:
return mylist.orderby(keyvalue);
don't forget add this: using extensionmethods;
Comments
Post a Comment