> Contains(str...">

"Doesn't contain" dynamic lambda expression

In the code below, the expression "Contain":

private static Expression<Func<T, bool>> Contains<T>(string property, string value) { var obj = Expression.Parameter(typeof(T), "obj"); var objProperty = Expression.PropertyOrField(obj, property); var contains = Expression.Call(objProperty, "Contains", null, Expression.Constant(value, typeof(string))); var lambda = Expression.Lambda<Func<T, bool>>(contains, obj); return lambda; } 

I am not very familiar with expressions, and I don’t know how to put negation in an expression function and cannot find a suitable method in the Expression class. Is there a similar way to create an expression "Does not contain" dynamically?

+6
source share
2 answers

A "does not contain" expression is exactly the same as the expression "does contains", but the unary negation wrapped in the expression. So basically you want:

 // Code as before var doesNotContain = Expression.Not(contains); return Expression.Lambda<Func<T, bool>>(doesNotContain, obj); 
+9
source

Contains returns you a bool . Inverting a bool is done using the Expression.Not method.

+3
source

Source: https://habr.com/ru/post/972947/


All Articles