为选择器创建表达式树 [英] Create Expression Tree For Selector

查看:61
本文介绍了为选择器创建表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关:

创建具有3个条件的Lambda表达式

将包含的内容转换为表达式树

转换列表.包含表达式树

请考虑上述问题.

我想为此查询:

using (MyEntities context = new MyEntities())
{
     var DbSet = context.CreateObjectSet<T>();
     var Max = DbSet.Where(exp).Select(selector).Max();
}

我不知道如何为selector编写代码.我应该使用什么Select重载?以及如何使用表达式树"编写它?

I don't know how to write a code for selector. What Select overload I should use? and How I can write that using Expression Tree?

谢谢

推荐答案

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

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;

这篇关于为选择器创建表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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