1

I would like to extend and to an existing expression by adding to it. So logically I want 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:

{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]):

{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. 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. Let me know if you need more info.

Rubans
  • 4,188
  • 6
  • 40
  • 58
  • [LINQPad](https://www.linqpad.net/) is very helpful with it's `Dump` method for examining `Expression` objects and seeing their properties. [LINQKit](https://github.com/scottksmith95/LINQKit) has methods for doing this for querying. See also my answer [here](https://stackoverflow.com/a/49928256/2557128) for another approach. – NetMage Apr 27 '18 at 17:32

1 Answers1

3

You can use UnaryExpression.Operand property.

In your scenario, I guess you want to get the predicate lambda expression. Which for IQueryable<T> source is wrapped in UnaryExpression by Expression.Quote method. 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.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343