c# - 将表达式树从等于转换为包含

标签 c# linq

在我的服务器中,我目前有一个方法来检查对象的字段是否等于给定的字符串,它看起来像这样:

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”。我怎样才能做到这一点?

最佳答案

使用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
);

关于c# - 将表达式树从等于转换为包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004669/

相关文章:

c# - 查找字符串中包含属性值的 XmlNode

c# - Sum(with Coalesce) with Group By in linq (for EF6)

c# - Linq All 在空集合上

c# - 为什么 List<>.OrderBy LINQ 在 Debug模式下比 IComparable+List<>.Sort 更快?

c# - 你如何在 WPF 中组织你的模型/ View / View 模型

c# - Windows 窗体 : Pass clicks through a partially transparent always-on-top window

c# - C# Newtonsoft 中的 JSON 数组迭代

c# - 在 C# 中动态实例化遗留 COM 对象(在字符串中使用其 ID)

c# - 如何在 Windows Vista/7/8 上以编程方式启动 SFC?

c# - 从表单更新 LINQ 模型的最佳方法