Search code examples
c#lambdaexpression-trees

Trying to build lambda tree


I'm trying to build an expression that must create query of type WHERE IN () For IN I must check if value exist in a list, so my expression looks like:

long loKey = 2;
List<long> loKeys = new List<long>();
loKeys.Add(loKey);

ParameterExpression parameter = Expression.Parameter(type, "t");
var constantExpression = Expression.Constant((List<long>)loKeys, typeof(List<long>));
var lambda = Expression.Lambda(
    typeof(Func<,>).MakeGenericType(type, typeof(bool)),
    Expression.Equal(
        Expression.Property(parameter, "ID"),
        constantExpression
    ),
    parameter
);
resultQuery = resultQuery.Provider.CreateQuery(
    Expression.Call(
        typeof(Queryable), 
        "Where",
        new Type[] { type },
        resultQuery.Expression,
        lambda
    ) 
);

So the idea is that field ID must exist in list loKeys, but I'm getting an error:

Additional information: The binary operator Equal is not defined for the types 'System.Int64' and 'System.Collections.Generic.List`1[System.Int64]'.

On Expression.Lambda -> MakeGenericType


Solution

  • So you are trying to build something like this:

    t => loKeys.Contains(t.ID)
    

    The only thing you need to consider is that actually Contains is a static extension method defined in Enumerable class:

    var lambda = Expression.Lambda(
        Expression.Call(
            typeof(Enumerable), 
            "Contains", 
            new[] { typeof(long) },
            Expression.Constant(loKeys),
            Expression.Property(parameter, "ID")
        ),
        parameter
    );