string ob = "f.Name";
var abc = from f in files
orderby(ob)
select f;
其中,orderby(ob) 显然不工作,怎么解决?
实际应用时,我要根据gridview的column header来排序,所以要pass header text 到 linq,然后再绑定gridview.
------解决方案--------------------------------------------------------
如果用的多得话,可以看看下面的库
Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
------解决方案--------------------------------------------------------
- C# code
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