我有一个按对象字段排序通用列表的方法:
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;
}
有什么方法可以将这些ifs折叠成一个通用语句?
主要问题是该部分
Expression.Lambda<Func<T, int>>
我不知道如何一般地写它。
答案 0 :(得分:3)
如果将Queryable.OrderBy
展开到其定义,那么您不必使用Expression.Lambda
的泛型重载:
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));
}
答案 1 :(得分:0)
这不会起作用吗?
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;
}