如何为多列OrderBy表达式创建表达式树 [英] How to create Expression Tree for multiple column OrderBy Expression
问题描述
我为EF通用存储库创建了一个orderby表达式,如下所示字符串命令= orderByDesc?"OrderByDescending":"OrderBy";
I have create an orderby expression for my EF generic Repository as following string command = orderByDesc ? "OrderByDescending" : "OrderBy";
var type = typeof(T);
var property = type.GetProperty(orderby);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
items.Expression, Expression.Quote(orderByExpression));
items = items.Provider.CreateQuery<T>(resultExpression);
现在,我想创建包含2列的表达式以进行订购,但找不到有用的东西.
Now I want to create the Expression with 2 columns for ordering and wasn't able to find out something helpful.
请帮助我创建一个包含2列的orderby表达式.
Please help me to create an orderby expression with 2 columns.
推荐答案
通过调用 OrderBy()
,然后零次或多次调用 ThenBy()<,LINQ中的多列排序可以工作/code>.您无法通过单次调用
OrderBy()
来做到这一点.
Ordering by multiple columns in LINQ works by calling OrderBy()
followed by zero or more calls to ThenBy()
. You can't do this using a single call to OrderBy()
.
例如,如果您想按 a
和 b
列进行排序,则必须生成一个类似于以下内容的表达式:
For example, if you can want to sort by the columns a
and b
, you will have to generate an expression that looks something like:
items.OrderBy(p => p.a).ThenBy(p => p.b)
这篇关于如何为多列OrderBy表达式创建表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!