2010-08-07 47 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