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

时间:2010-08-07 18:49:20

标签: c# dynamic lambda expression predicates

我正在尝试创建动态谓词,以便可以对列表进行过滤

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

我希望能够创建动态谓词,以便可以过滤List。我得到一些条件作为字符串值“>”,“<”,“> =”等等。有没有办法可以做到这一点?

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?以及如何在其中创建谓词?

1 个答案:

答案 0 :(得分:14)

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();
    }
}

有任何问题吗? : - )