Invert the Expression<Func<T, bool>>
Asked Answered
B

1

8

I'm writing the expression extensions method which must inverse the bool-typed lambda expression.

Here is what I am doing:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e));
}

But this raises an exception, that unary operator is NOT not defined for the type Func<int,bool>. I also tried this:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body));
}

But getting this: Incorrent number of parameters supplied for lambda declaration.

Beholden answered 17/12, 2012 at 9:51 Comment(0)
B
21

Fortunately, this is solved this way:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body), e.Parameters[0]);
}

Which indicates that .Lambda<> method needs a parameter, which we need to pass it from source expression.

Beholden answered 17/12, 2012 at 9:51 Comment(3)
If there isn't any parameters, you should be able to pass null I think? Like when you do Method.Invoke, just curious if that is the case.Lentha
e.Parameters[0] will throw exception, if no parameters defined.Burkle
@HamletHakobyan there is no way to specify no parameters since the generic type of this extension is Func<T, bool>, where T is the parameter. Passing null will result the extracting that null, not raising the IndexOutOfBounds or any other exception.Beholden

© 2022 - 2024 — McMap. All rights reserved.