I have a list of field names. I am trying to build a predicate to look in the fields to see if they contain the search term. I have gone done the path listed in this original question but do not understand how to do a Contains instead of a NotEqual.
string searchTerm = "Fred";
foreach (var field in FieldNames)
{
myPredicate= myPredicate.And(m => m.*field*.Contains(searchTerm));
}
My code so far:
public static Expression<Func<T, bool>> MultiColumnSearchExpression<T>(string fieldName,string searchValue)
{
var parameter = Expression.Parameter(typeof(T), "m");
var fieldAccess = Expression.PropertyOrField(parameter, fieldName);
//this next line should do a Contains rather then NotEqual but how?
var body = Expression.NotEqual(fieldAccess, nullValue);
var expr = Expression.Lambda<Func<T, bool>>(body, parameter);
return expr;
}
So you want to call
String.Contains
method.It is a
String
class instance method with the following signaturewhich can be mapped to the following
Expression.Call
overload:And here is how:
Expression.NotEqual
is the binary operator!=
. Since yourContains
call is not a binary operator, there is no direct replacement for this.Instead, what you need to do is a method call of
Contains
. So you first need to get theMethodInfo
object for thestring.Contains
function.It should look like this: