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

Luk*_*ett 3 c# linq linq-to-objects

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

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

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

Luk*_*ett 13

代码优先,稍后解释.

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 }));
Run Code Online (Sandbox Code Playgroud)

因此,首先我们将数据保存为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]
 })
Run Code Online (Sandbox Code Playgroud)

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

卢克