c# - 根据作为字符串列表的属性过滤数据的表达式

标签 c# lambda expression

我有以下代码:

case FilterQueryType.Contains:
      var parameterExp = Expression.Parameter(type, "type");
      var propertyExp = Expression.Property(parameterExp, filter.PropertyName);
      var containsConstExp = Expression.Constant(filter.MyKeyword);
      MethodInfo method = typeof(string).GetMethod("Contains", new []{typeof(string)});
      var containsMethodExp = Expression.Call(propertyExp, method, containsConstExp);
      var containsLambda = Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
      items = items.Where(containsLambda);
      break;

只要 filter.PropertyName 是一个字符串,这段代码就可以正常工作。 现在我有一个例子,其中 filter.PropertyName 实际上是一个可枚举的字符串。

有人能告诉我如何为此创建正确的表达式吗? (filter.MyKeyword 本身将始终是单个值)

最佳答案

 MemberExpression memberExpression = Expression.Property(parameterExp, filter.PropertyName);
 Expression convertExpression = Expression.Convert(memberExpression, typeof(List<string>));
 MethodCallExpression containsExpression = Expression.Call(convertExpression, "Contains", new Type[] { }, constExpr);
 lambda = Expression.Lambda<Func<T, bool>>(containsExpression, parameterExp);
 items = items.Where(lambda);

这个解决方案适合我

关于c# - 根据作为字符串列表的属性过滤数据的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443092/

相关文章:

C++ lambda 作为参数。错误 : use of deleted function

javascript - 返回 Promise.all 不执行提供的 Promise

c# - 获取文本框行号

c# - 使用 LINQ LAMBDA 让每个部门的员工

c# - 有效处理 C# 方法中的单个值和多个值

java - 简单教程示例(lambda 表达式)不运行

c# - 当子控件 ManipulationMode 设置为 'None' 以外的值时,父控件将失去操作功能

javascript - 如何验证 JavaScript 中的中缀表示法?

c++ - 存储表达式模板仿函数

c++ - C++ 中 std::cout 的奇怪行为