我有一种方法可以通过对象字段对通用列表进行排序:
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;
}
有没有办法将这些if语句合并为一个通用语句?
主要问题在于对于部分Expression.Lambda<Func<T, int>>
,我不确定如何编写通用代码。