7

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

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

4

1 回答 1

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

任何问题?:-)

于 2010-08-07T19:03:35.160 回答