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

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

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

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

代码优先,稍后解释。

IQueryable data = this.Database.ObjectsOfType(); 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>(propertyToOrderByExpression, new ParameterExpression[] { eachItem })); 

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

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

然后我们创建一个表达式,对read操作执行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,因为该属性可以是任何类型,但显然需要与可订购相媲美。

卢克