繁体   English   中英

如何组合Linq表达式在一组实体上调用OrderBy?

[英]How to a compose a Linq Expression to call OrderBy on a set of entities?

有人可以解释构建一个表达式的语法,该表达式将在一个实体上使用OrderBy用户指定的属性吗?

这篇MSDN文章有很长的路要走,但它处理一个简单的字符串列表,我的数据集包含我自己的自定义对象。

http://msdn.microsoft.com/en-us/library/bb882637.aspx

代码优先,稍后解释。

IQueryable<T> data = this.Database.ObjectsOfType<T>();

var eachItem = Expression.Parameter(typeof(T), "item");
var propertyToOrderByExpression = Expression.Property(eachItem, propertyName);

var runMe = Expression.Call(
    typeof(Queryable),
    "OrderBy",
    new Type[] { data.ElementType, typeof(IComparable) },
    data.Expression,
    Expression.Lambda<Func<T,IComparable>>(propertyToOrderByExpression, new ParameterExpression[] { eachItem }));

因此,首先我们将数据保存为Queryable对象。 这有一种'root'表达式属性,我们需要它。

eachItem是一个表达式,表示Lambda中的参数占位符,如果愿意,则表示转到的符号。

然后我们创建一个表达式,它将读取操作作为propertyName中用户指定的属性名称。

我们最终构建了一个表达式,它在Queryable数据上调用OrderBy方法。 我们说(按照论点的顺序):

Expression.Call(
 [what's the type on which we want to call a method?],
 [what's the name of the method we're calling?],
 [if this method is generic, what are the types it deals with?],
 {
  [expression representing the data],
  [expression for the lambda using the reader exp + each item exp]
 })

最后两个是{},因为它实际上是一个param数组。 我使用IComparable,因为该属性可以是任何类型,但显然需要与可订购的类似。

卢克

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM