c# - How do I write a Dynamic LINQ query and have Orderby [Sort Direction] -
i write linq query similar sql query:
select id, title, description, date sometable
and add 'orderby' , 'ascending/descending' dynamically.
i need add sort functionality on gridview, datasource linq query.
you write own sortby
extension method takes sortdirection
.
public enum sortdirection { ascending, descending } public static class extensions { public static ienumerable<tsource> sortby<tsource, tkey>( ienumerable<tsource> source, sortdirection sortdirection, func<tsource, tkey> keyselector) { switch (sortdirection) { case sortdirection.ascending: return source.orderby(keyselector); case sortdirection.descending: return source.orderbydescending(keyselector); default: throw new argumentoutofrangeexception(); } }
usage
var sortdirection = sort.descending; // set dynamically @ runtime var sorted = new[] { 1, 2, 3 }.sortby(sortdirection.descending, x => x);
Comments
Post a Comment