日期:2014-05-18 浏览次数:20539 次
public class TestD
{
public int ID { get; set; }
public string Name { get; set; }
}
public static IQueryable<T> OrderSort<T>(IQueryable<T> Sour, string SortExpression, string Direction)
{
string SortDirection = string.Empty;
if (Direction == "asc")
SortDirection = "OrderBy";
else if (Direction == "desc")
SortDirection = "OrderByDescending";
ParameterExpression pe = Expression.Parameter(typeof(T), SortExpression);
PropertyInfo pi = typeof(T).GetProperty(SortExpression);
Type[] types = new Type[2];
types[0] = typeof(T);
types[1] = pi.PropertyType;
Expression expr = Expression.Call(typeof(Queryable), SortDirection, types, Sour.Expression, Expression.Lambda(Expression.Property(pe, SortExpression), pe));
IQueryable<T> query = Sour.Provider.CreateQuery<T>(expr);
return query;
}
static void Main(string[] args)
{
List<TestD> list = new List<TestD>() { new TestD() { ID = 1, Name = "a" }, new TestD() { ID = 2, Name = "b" } };
var linq = (from l in list select l).AsQueryable<TestD>();
OrderSort<TestD>(linq, "ID", "desc").ToList<TestD>().ForEach(x => Console.WriteLine("{0} {1}", x.ID, x.Name));
Console.ReadLine();
}
------解决方案--------------------
这个用反射即可解决嘛
linq 实现动态 orderby
OR:
Dynamic LINQ