如何在撰写LINQ表达式来调用排序依据上一个实体的集合?(How to a compose a Li

2019-07-31 06:58发布

有人可以解释为构建将ORDERBY对实体用户指定属性的表达式的语法?

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

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

Answer 1:

代码首先,解释以后。

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 }));

因此,首先我们得到的数据,可查询对象的保持。 这有一种“根”表达性,我们需要这一点。

该eachItem的是代表一个lambda参数占位符表达式,在符号去,如果你愿意。

然后,我们作出这样做的读操作由propertyName的用户指定的属性名称的表达式。

最后,我们建立这确实调用的可查询数据的排序依据方法的表达。 我们说,(在辩论的顺序排列):

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]
 })

最后两个是{}因为它实际上是一个参数数组。 我用IComparable的,因为财产可以是任何类型,但显然需要相当订购。

卢克



文章来源: How to a compose a Linq Expression to call OrderBy on a set of entities?