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

断了今生、忘了曾经 提交于 2019-12-06 08:59:26

问题


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

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


回答1:


Code first, explanation later.

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

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

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

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

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.

Luke



来源:https://stackoverflow.com/questions/12219404/how-to-a-compose-a-linq-expression-to-call-orderby-on-a-set-of-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!