且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为选择器创建表达式树

更新时间:2023-02-16 12:56:04

我应该使用什么选择超载?

What Select overload I should use?

除了单个参数外的那个到源头:

public static IQueryable<TResult> Select<TSource, TResult>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, TResult>> selector
)

如何使用表达式树"将其编写出来?

How can I write that using Expression Tree?

选择器需要采用TSource参数,并产生要检索Max的字段.例如,假设TSource的类型为Employee,而您想查找其Salary属性的Max类型为decimal.然后,您将创建一个表达式树,如下所示:

Selector needs to take a TSource parameter, and produce the field of which you want to retrieve the Max. For example, let's say TSource is of type Employee, and you want to find the Max of its Salary property of type decimal. Then you would create an expression tree like this:

var p = Expression.Parameter(typeof(Employee));
var m = Expression.Property(p, "Salary");
var e = Expression.Lambda(m, p);
var selector = (Expression<Func<Employee,decimal>>)e;