I need to create an Expression to search one string not contains another. I was able to create it for contains method:
return Expression.Call(firstOrDefaultCall, typeof(string).GetMethod("Contains"), Expression.Constant(text));
how to convert it to 'not contains'?
How would you normally write it?
var stringValue = "foo"
var result = !stringValue.Contains("o");
Notice the logical negation operator !
before Contains()
. That's the only part you are missing. To negate a boolen value when building an expression, use Expression.Not()
:
return Expression.Not(
Expression.Call(
firstOrDefaultCall,
typeof(string).GetMethod("Contains"),
Expression.Constant(text)));
And don't fall into trap of using Expression.Negate()
. That one is for an arithmetic negation operation, example of arithmetic negation:
var negatedPi = Math.PI * -1;