我对由对象字段排序泛型列表的方法:创建排序功能的通用列表
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>>
我不知道如何一般地写它。
http://stackoverflow.com/questions/41244/dynamic-linq-orderby – 2010-04-15 15:48:57