我怎么可以在我的LINQ CompiledQuery动态ORDERBY(如供应订单场和方向作为编译的查询参数)?
Answer 1:
我想我找到它:
看看这个链接 。 这将指向你包含动态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);
}
Answer 2:
我会做这种方式,首先你真正需要的是通过字符串来访问对象的属性值的方式。 你可以使用反射,但其缓慢的。 所以使用的是基于测试这个助手类方法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"));
希望这可以帮助。
文章来源: Dynamic Order (SQL ORDERBY) in LINQ CompiledQuery