Creating a sort function for a shared list

I have a method for sorting general lists by object fields:

public static IQueryable<T> SortTable<T>(IQueryable<T> q, string sortfield, bool ascending) { var p = Expression.Parameter(typeof(T), "p"); if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int?)) { var x = Expression.Lambda<Func<T, int?>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int)) { var x = Expression.Lambda<Func<T, int>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(DateTime)) { var x = Expression.Lambda<Func<T, DateTime>>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } // many more for every type return q; } 

Is there any way to collapse these ifs into one common statement? The main problem is that for the Expression.Lambda<Func<T, int>> part Expression.Lambda<Func<T, int>> I am not sure how to write it as a whole.

+3
generics c #
source share
2 answers

If you expand Queryable.OrderBy into its definition, you do not have to use Expression.Lambda generic overload:

 public static IQueryable<T> SortTable<T>( IQueryable<T> q, string sortfield, bool ascending) { var p = Expression.Parameter(typeof(T), "p"); var x = Expression.Lambda(Expression.Property(p, sortfield), p); return q.Provider.CreateQuery<T>( Expression.Call(typeof(Queryable), ascending ? "OrderBy" : "OrderByDescending", new Type[] { q.ElementType, x.Body.Type }, q.Expression, x)); } 
+3
source share

Would this work?

  public static IQueryable<T> SortTable<T>(IQueryable<T> q, string sortfield, bool ascending) { var type = typeof(T).GetProperty(sortfield).PropertyType; var p = Expression.Parameter(typeof(T), "p"); var x = Expression.Lambda<Func<T, type> >(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); return q; } 
0
source share

All Articles