2009-09-15 36 views

回答

1

我想我找到它:

看看这个link。它将向您指出包含动态Linq查询库的VS2008代码示例,其中包含下面的扩展方法。这将允许你去:

Object.OrderBy("ColumnName"); 

这里是扩展方法,但你可能想要整个库。

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) { 
    return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values); 
} 

public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) { 
    if (source == null) throw new ArgumentNullException("source"); 
    if (ordering == null) throw new ArgumentNullException("ordering"); 
    ParameterExpression[] parameters = new ParameterExpression[] { 
     Expression.Parameter(source.ElementType, "") }; 
    ExpressionParser parser = new ExpressionParser(parameters, ordering, values); 
    IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering(); 
    Expression queryExpr = source.Expression; 
    string methodAsc = "OrderBy"; 
    string methodDesc = "OrderByDescending"; 
    foreach (DynamicOrdering o in orderings) { 
     queryExpr = Expression.Call(
      typeof(Queryable), o.Ascending ? methodAsc : methodDesc, 
      new Type[] { source.ElementType, o.Selector.Type }, 
      queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters))); 
     methodAsc = "ThenBy"; 
     methodDesc = "ThenByDescending"; 
    } 
    return source.Provider.CreateQuery(queryExpr); 
} 
+2

虽然这不能被编译(CompiledQuery.Compile())。 – Alex 2009-09-24 06:07:12

1

我会这样做,首先你真正需要的是一种通过对象上的字符串访问属性值的方法。你可以使用反射,但它很慢。因此,使用了基于http://stefan.rusek.org/Posts/LINQ-Expressions-as-Fast-Reflection-Invoke/3/

public static class LINQHelper 
    { 
     public static IComparable OrderByProperty<TClass>(TClass item, 
                  string propertyName) 
     { 
      var t = Expression.Parameter(typeof(TClass), "t"); 
      var prop = Expression.Property(t, propertyName); 
      var exp = Expression.Lambda(prop, t).Compile(); 
      return (IComparable)exp.DynamicInvoke(item); 
     } 

    } 

的在你的代码,你的属性名称的字符串,希望你为了测试这种辅助类的办法,在这个例子中COL1,你只要做到以下几点。

 var myQuery = from i in Items 
        select i; 

    myQuery.OrderBy(i=>LINQHelper.OrderByProperty(i,"col1")); 

希望这会有所帮助。