Convert List.Contains to Expression Tree

前端 未结 2 781
情歌与酒
情歌与酒 2021-01-27 13:19

Related To:

Create a Lambda Expression With 3 conditions

Convert Contains To Expression Tree

In the following of my previous question I faced with this

相关标签:
2条回答
  • 2021-01-27 13:39

    The problem is that you have switched two arguments to Expression.Call, your code is trying to create the nonsensical expression o.Status.Contains(lst).

    You need to switch the two arguments around:

    Expression.Call(Expression.Constant(lst),
        "Contains",
        Type.EmptyTypes, 
        Expression.PropertyOrField(param, "Status"))
    

    This is assuming that the LINQ provider you're using understands List<T>.Contains(). If you need Enumerable.Contains(), then have a look at Ivan Stoev's answer.

    0 讨论(0)
  • 2021-01-27 13:44

    The difference from Convert Contains To Expression Tree is that there we were calling a string instance Contains method, while here we need to call a static generic method Enumerable.Contains:

    public static bool Contains<TSource>(
        this IEnumerable<TSource> source,
        TSource value
    )
    

    It can be achieved by using another Expression.Call overload:

    public static MethodCallExpression Call(
        Type type,
        string methodName,
        Type[] typeArguments,
        params Expression[] arguments
    )
    

    like this:

    // Enumerable.Contains<byte?>(lst, a.Status)
    var containsCall = Expression.Call(
        typeof(Enumerable), // type
        "Contains", // method
        new Type[] { typeof(byte?) }, // generic type arguments (TSource)
        Expression.Constant(lst),  // arguments (source)
        Expression.PropertyOrField(param, "Status")  // arguments (value)
    );
    
    0 讨论(0)
提交回复
热议问题