简体   繁体   English

从UnaryExpression C#获取Linq.Expression的主体

[英]Get Linq.Expression's Body from a UnaryExpression C#

I would like to extend and to an existing expression by adding to it. 我想通过添加到现有表达式来扩展它。 So logically I want exp3: 所以逻辑上我想要exp3:

exp1 = o => (((o.AuditDateTime > 10/04/2018 00:00:00) && (o.AuditDateTime < 18/04/2018 00:00:00)))
exp2 = o => (o.EventType == "X")
exp3 = o => (((o.AuditDateTime > 10/04/2018 00:00:00) && (o.AuditDateTime < 18/04/2018 00:00:00))) && (o.EventType == "X")

I have IQueryable instance with a defined where Expression already, something like: 我有一个已经定义了Expression的IQueryable实例,类似于:

{AuditJournalEntity[].Where(o => (((o.AuditDateTime > 10/04/2018 00:00:00) AndAlso (o.AuditDateTime < 18/04/2018 00:00:00))))}

So I can grab the actual where expression it self using Arguments array (Arguments[1]): 因此,我可以使用Arguments数组(Arguments [1])来获取它本身的实际where表达式:

{o => (((o.AuditDateTime > 10/04/2018 00:00:00) AndAlso (o.AuditDateTime < 18/04/2018 00:00:00)))}

However, I don't know how to grab the expression body part of the UnaryExpression so that I can add to it later on. 但是,我不知道如何获取UnaryExpression的表达式主体部分,以便稍后再添加。 What I want is this part: 我想要的是这部分:

(((o.AuditDateTime > 10/04/2018 00:00:00) AndAlso (o.AuditDateTime < 18/04/2018 00:00:00)))

If in debug, it is able to give this part using something UnaryExpressionProxy instance but it's a private member I think so can't really use that. 如果在调试中,它可以使用UnaryExpressionProxy实例来提供此部分,但是我认为它是私有成员,因此不能真正使用它。 Let me know if you need more info. 让我知道您是否需要更多信息。

You can use UnaryExpression.Operand property. 您可以使用UnaryExpression.Operand属性。

In your scenario, I guess you want to get the predicate lambda expression. 在您的方案中,我想您想获取谓词lambda表达式。 Which for IQueryable<T> source is wrapped in UnaryExpression by Expression.Quote method. IQueryable<T>源的哪一个通过Expression.Quote方法包装在UnaryExpression So you can use something like this: 因此,您可以使用如下所示的内容:

static LambdaExpression ExtractLambda(Expression source)
{
    while (source != null && source.NodeType == ExpressionType.Quote)
        source = ((UnaryExpression)source).Operand;
    return source as LambdaExpression;
}

Then you can get the body using the LambdaExpression.Body property. 然后,您可以使用LambdaExpression.Body属性获取主体。

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

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