1

I try to concatenate 2 lambda expressions that are generated dynamically:

public Expression<Func<User, bool>> Expres(int id)
{
    var argument = Expression.Parameter(typeof(User));
    var left = Expression.Property(argument,"id");
    var right = Expression.Constant(id);
    BinaryExpression binary = Expression.Equal(left, right);
    Expression<Func<User, bool>> exp = Expression.Lambda<Func<User, bool>>(
        binary,
        new[] { argument }
    );

    return exp;
}

Example:

>Expres(255);
Param_0.id == 255

>Expres(10);
Param_0.id == 10

but, when merge them...

>expression = Expression.And(exp1, exp2);

(Param_0.Id == 255) And (Param_1.Id == 10)

>Expression.Lambda<Func<TEntidad, bool>>(expression, new[] { argument });

Param_0 => ((Param_1.Id == 255) And (Param_2.Id == 10)

but it generates more dependencies than required, and the result of what I expected is:

Param_0 => ((Param_0.Id == 255) And (Param_0.Id == 10)

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • I see that you don't search on [SO](https://stackoverflow.com/search?q=%5Bc%23%5D+%5Bexpression%5D+parameter) yet. So I just put the [one of solution](https://stackoverflow.com/questions/45765350/create-predicate-with-a-binaryexpression-containing-multiple-parameters/45766150#45766150). Main problem is that you have two expression that are contain two different input parameter, so you just need to swap their parameters at the one common. `SwapVisitor` you can find by the link above. – George Alexandria Mar 09 '18 at 17:18
  • 1
    The summarize, `argument` is a different instance in each expression. If you want them to refer to the same thing, you will need both expressions to share a reference to the same `Expression.Parameter` instance. – Bradley Uffner Mar 09 '18 at 17:28

0 Answers0