2

I have one expression that's defined like this:

Expression<Func<T1, T2, bool>> firstExpression;

and another one like this one:

Expression<Func<T1, bool>> secondExpression;

T2 is a value I know, T1 isn't. What I would like is to make the first expression into the second one, given the value of the parameter T2. If it would be regular Linq, it would be this:

var t2 = "Something I know";
secondExpression = t1 => fistExpression(t1, t2);

How would I do this using System.Linq.Expressions?

3 Answers 3

2

You can accomplish this with expression visitor:

public static class EmitUtils
{
        private class ParameterReplacerVisitor : ExpressionVisitor
        {
            private ParameterExpression _source;
            private Expression _target;

            public ParameterReplacerVisitor(ParameterExpression source, Expression target)
            {
                _source = source;
                _target = target;
            }

            public override Expression Visit(Expression node) =>
                node == _source
                    ? _target
                    : base.Visit(node);
        }

        public static Expression ReplaceParameter(Expression body, ParameterExpression srcParameter, Expression dstParameter) =>
            new ParameterReplacerVisitor(srcParameter, dstParameter).Visit(body);

        public static Expression<Func<T1, T3>> BuildClosure<T1, T2, T3>(Expression<Func<T1, T2, T3>> src, T2 closureValue)
        {
            var constExpression = Expression.Constant(closureValue, typeof(T2));
            var body = ReplaceParameter(src.Body, src.Parameters[1], constExpression);
            return Expression.Lambda<Func<T1, T3>>(body, src.Parameters[0]);
        }

    }

Here is sample usage:

        [Test]
        public void ClosureTest()
        {
            Expression<Func<int, string, bool>> CheckStringLength = (len, str) => str.Length < len;
            var constString = "some string";
            var result = EmitUtils.BuildClosure(CheckStringLength, constString);
            Assert.That(result.Compile().Invoke(100), Is.True);
        }
0

You can do it by swapping parameter expression with constant expression. Should looks like this

  1. implement custom swap ExpressionVisitor

    public class SwapVisitor : ExpressionVisitor
    {
        public Expression From { get; set; }
        public Expression To { get; set; }
    
        public override Expression Visit(Expression node)
        {
            return node == From ? To : base.Visit(node);
        }
    }
    
  2. replace parameter T2 with constant

    var swapper = new SwapVisitor
    {
      From = fistExpression.Parameters[1],
      To = Expression.Constant(val)
    };
    
    var result = Expression.Lambda<Func<T, bool>>(
       swapper.Visit(fistExpression.Body), 
       fistExpression.Parameters[0]);
    
0
0

Consider the following sample(firstLambda ans secondExpression needed just to see how compiler build the expression)

using System;
using System.Linq.Expressions;

static void Main(string[] args)
{
    Expression<Func<string, int, bool>> firstExpression = (a, b) => a == b.ToString();

    Func<string, int, bool> firstLambda = (a, b) => a == b.ToString();
    Expression<Func<string, bool>> secondExpression = s => firstLambda(s, 45); // this expression I need just to see how it is compiled


    var inputParameter = Expression.Parameter(typeof(string), "s");

    var invocation = Expression.Invoke(firstExpression, inputParameter, Expression.Constant(47));

    var ourBuildExpression = Expression.Lambda<Func<string, bool> > (invocation, new ParameterExpression[] { inputParameter }).Compile();

    Console.WriteLine(ourBuildExpression("45"));
    Console.WriteLine(ourBuildExpression("47"));

    Console.ReadKey();
}

I checked in the debugger watch window the result of Expression<Func<string, bool>> secondExpression = s => firstLambda(s, 45); it was Invoke expression, so I constructed the same manually.

And you can see the test calls return and print False and True as expected.

1
  • Yes this works, but there's one catch: Expression.Invoke doesn't work with most query providers... Sep 27, 2019 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.