Reputation: 1335
In my server I currently have a method that checks if the field of an object equals a given string, and it looks like this:
var parameter = Expression.Parameter(typeof(Book), "b");
var predicate = Expression.Lambda<Func<Book, bool>>(Expression.Equal(Expression.PropertyOrField(parameter, filterAfter), Expression.Constant(filterField)),parameter);
To exemplify, if filterAfter is "title" and filterField is "Castle", then the expression will do book.title == "Castle". What I want to do is to convert the expression above to check if book.title contains the substring "Castle" in the title. How can I achieve that?
Upvotes: 2
Views: 296
Reputation: 726709
Use Expression.Call
var containsMethod = typeof(string).GetMethod(nameof(string.Contains), new[] {typeof(string)});
var predicate = Expression.Lambda<Func<Book, bool>>(
Expression.Call(
Expression.PropertyOrField(parameter, filterAfter)
, containsMethod
, new Expression[] { Expression.Constant(filterField) }
)
, parameter
);
Upvotes: 1