2010-08-07 40 views
7

我想创建动态谓词,以便它可以对一个列表用于过滤创建动态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界定?以及如何在里面创建谓词?

回答

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

有没有问题? :-)

+0

谢谢!有效! – venkod 2010-08-07 19:38:09