Creating Dynamic Predicates- passing in property t

2019-01-22 16:16发布

I am trying to create dynamic predicate so that it can be used against a list for filtering

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

I want to be able to create a dynamic predicate so that a List can be filtered. I get few conditions as string values ">","<",">=" etc. Is there a way by which I can do this?

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
            }               
 }

and the usage could be:

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

How should the GetFilter be defined? and how to create the predicate inside that?

1条回答
Emotional °昔
2楼-- · 2019-01-22 16:50
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();
    }
}

Any questions? :-)

查看更多
登录 后发表回答