简体   繁体   English

如何将表达式转换为 lambda 表达式?

[英]How do I convert an Expression to a lambda expression?

I am trying to convert an Expression of type Expression<Func<Entity, bool>> to a Func<Entity, bool> .我正在尝试将Expression<Func<Entity, bool>>类型的表达式转换为Func<Entity, bool>

The background here is that I am trying to mock a repository so that it will return one of a collection of mock entities for a given key value.这里的背景是我正在尝试模拟存储库,以便它将返回给定键值的模拟实体集合之一。 (I could hard code the input values to the mocked method but this seems like the wrong approach for a large number of items). (我可以将输入值硬编码为模拟方法,但这对于大量项目来说似乎是错误的方法)。

So I am trying to mock the First method on my repository like this:所以我试图在我的存储库中模拟第一个方法,如下所示:

var collection = new List<Entity> 
{ 
    mockedEntity1, 
    mockedEntity2, 
    mockedEntity3, 
    ... 
};

mockRepository
    .Setup(rep => rep.First(It.IsAny<Expression<Func<Entity, bool>>>()))
    .Returns<Expression<Func<Entity, bool>>>(e => collection.First(e));

This doesn't work because collection.First takes a Func rather than an Expression>.这不起作用,因为 collection.First 采用 Func 而不是 Expression>。 So I have got to the point where I need to convert the Expression to the Func that it contains.所以我已经到了需要将 Expression 转换为它包含的 Func 的地步。

Perhaps there a simpler or better to do this?也许有更简单或更好的方法来做到这一点?

You need to call Compile on the expression.您需要在表达式上调用Compile

It already is a lambda expression.它已经lambda 表达式。 But to get a delegate from the lambda, call .Compile() .但要从 lambda 获得代表,请调用.Compile()

In the general sense - to make a lambda from an Expression you would use Expression.Lambda, indicating the desired type and including the parameter (declaration) instances (from Expression.Parameter).一般意义上 - 要从表达式生成 lambda,您将使用 Expression.Lambda,指示所需的类型并包括参数(声明)实例(来自 Expression.Parameter)。 However, this is not required here.但是,这里不需要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM