Creating Dynamic Predicates- passing in property to a function as parameter
Asked Answered
S

1

7

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?

Smalt answered 7/8, 2010 at 18:49 Comment(0)
P
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();
    }
}

Any questions? :-)

Phonography answered 7/8, 2010 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.