Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Does Not Contain" dynamic lambda expression

Tags:

c#

linq

The code below does "Contain" expression:

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 into the expression function and cannot find any suitable method in "Expression" class. Is there any similar way to create "Does Not Contain" expression dynamically?

like image 935
desperate man Avatar asked Jul 28 '14 10:07

desperate man


2 Answers

A "does not contain" expression is exactly the same as a "does contain" expression - but wrapped with a unary negation expression. So basically you want:

// Code as before
var doesNotContain = Expression.Not(contains);
return Expression.Lambda<Func<T, bool>>(doesNotContain, obj);
like image 158
Jon Skeet Avatar answered Oct 01 '22 08:10

Jon Skeet


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

like image 33
usr Avatar answered Oct 01 '22 07:10

usr