在我的服务器中,我目前有一个方法来检查对象的字段是否等于给定的字符串,它看起来像这样:
var parameter = Expression.Parameter(typeof(Book), "b");
var predicate = Expression.Lambda<Func<Book, bool>>(Expression.Equal(Expression.PropertyOrField(parameter, filterAfter), Expression.Constant(filterField)),parameter);
例如,如果 filterAfter 是“title”并且 filterField 是“CaSTLe”,那么表达式将执行 book.title == “CaSTLe”。我想要做的是转换上面的表达式以检查 book.title 是否包含标题中的子字符串“CaSTLe”。我怎样才能做到这一点?
最佳答案
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
);
关于c# - 将表达式树从等于转换为包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004669/