如何将一个撰写LINQ表达式来调用排序依据一组实体? [英] How to a compose a Linq Expression to call OrderBy on a set of entities?

查看:124
本文介绍了如何将一个撰写LINQ表达式来调用排序依据一组实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释的语法建设,将排序依据的实体用户指定属性的表达式?

Can someone explain the syntax for building an Expression that will OrderBy a user-specified property on an entity?

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

This MSDN article goes a long way to helping, but it deals with a simple list of strings, my data set contains my own custom objects.

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



所以,首先我们得到的数据,可查询的对象保持。这有一种根Expression属性的,我们需要的。

So, first we get hold of the data as a Queryable object. This has a kind of 'root' Expression property, and we need that.

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

The eachItem thing is an expression that represents the argument placeholder in a Lambda, the symbol in the goes to, if you will.

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

Then we make an expression that does the read operation the property name specified by the user in propertyName.

我们终于建立由它来调用上可查询的数据排序依据的方法表达。我们说,(在辩论的顺序排列):

We finally build an expression which does the call to the OrderBy method on the Queryable data. We're saying (in order of argument):

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的,因为财产可以是任何类型,但显然需要堪比订购。

The last two are in { } since its actually a param array. I used IComparable since the property could be any type but obviously needs to be comparable to be ordered.

这篇关于如何将一个撰写LINQ表达式来调用排序依据一组实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆