c# - 创建动态谓词 - 将属性作为参数传递给函数

标签 c# dynamic lambda expression predicates

我正在尝试创建动态谓词,以便它可以用于过滤列表

 public class Feature
 {
   public string Color{get;set;}
   public string Weight{get;set;}
 }

我希望能够创建一个动态谓词,以便可以过滤列表。我得到的条件很少,如字符串值“>”、“<”、“>=”等。有什么方法可以做到这一点吗?

public Predicate<Feature> GetFilter(X property,T value, string condition) //no clue what X will be
 {
            switch(condition)
            {
              case ">=":
               return new Predicate<Feature>(property >= value)//or something similar
            }               
 }

用法可能是:

 var filterConditions=GetFilter(x=>x.Weight,100,">=");

GetFilter 应该如何定义?以及如何在其中创建谓词?

最佳答案

public Predicate<Feature> GetFilter<T>(
    Expression<Func<Feature, T>> property,
    T value,
    string condition)
{
    switch (condition)
    {
    case ">=":
        return
            Expression.Lambda<Predicate<Feature>>(
                Expression.GreaterThanOrEqual(
                    property.Body,
                    Expression.Constant(value)
                ),
                property.Parameters
            ).Compile();

    default:
        throw new NotSupportedException();
    }
}

有什么问题吗? :-)

关于c# - 创建动态谓词 - 将属性作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431617/

相关文章:

c# - 扩展 Enumerable.Range

c# - 如何压缩文件夹中的所有文件

即使没有传递指针,线程中的所有函数都可以访问动态分配的内存(堆)吗?或者它是函数的本地函数吗?

javascript - 以特定方式循环动态 JSON

javascript - jQuery:根据动态添加的类选择元素?

c# - Entity Framework : Database. ExecuteSqlCommand 方法

c++ - 如何为参数为泛型类型的模板类中的方法定义函数签名

python - 类型错误 : <lambda>() missing 1 required positional argument: 'w'

java - 在带有空格的同一行中使用 Lambda foreach 进行打印

c# - 如何在不同的类中检查 WPF 元素的属性?