"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?
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); Contains returns you a bool . Inverting a bool is done using the Expression.Not method.