LINQ CompiledQuery中的动态订单(SQL ORDERBY) [英] Dynamic Order (SQL ORDERBY) in LINQ CompiledQuery
问题描述
如何在LINQ CompiledQuery中创建动态ORDERBY(例如,将订单字段"和方向"作为已编译查询的参数)?
how can I create a dynamic ORDERBY in my LINQ CompiledQuery (e.g. supply Order Field and Direction as parameters for the compiled query)?
推荐答案
我会这样做,首先,您真正需要的是一种通过对象上的字符串访问属性值的方法.您可以使用反射,但是反射很慢.因此,请使用基于 http://stefan.rusek.org/Posts/LINQ-Expressions-as-Fast-Reflection-Invoke/3/
I would do it this way, first all you really need is a way to access the property value by string on an object. You could use reflection, but its slow. So use this helper class approach which is based on the tests of 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中,您只需执行以下操作即可.
The in your code where you want your order by string of property name, in this example col1, you just do the following.
var myQuery = from i in Items
select i;
myQuery.OrderBy(i=>LINQHelper.OrderByProperty(i,"col1"));
希望这会有所帮助.
这篇关于LINQ CompiledQuery中的动态订单(SQL ORDERBY)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!