0

I havea method that returns Expression to be used for dynamic filtering of records based on the clients needs, i have a problem in doing it, i want something like this

     public Expression<T> FilterCreator<T>(FilterCondition condition, string columnName, object value)
    {

        Expression<Func<Customer, bool>> query;

        // FilterCondition is an enum flag for conditions
        if(condition.Condition == ConditionFlags.EQUALS)
        {
            // here is the problem,
            // i want the emailAddress to be dynamic based on the passed columName parameter of the client 
            // and be able to cast its type of the value that was passed
            query = p => p.EmailAddress == (typeof(p.EmailAddress))value;

           //i want something like this
           // query = p => p.(columnName)=> (typeOf(p.(columnName)))value;

        }
        else if(condition.Condition == ConditionFlags.CONTAINS)
        {
             .....
        } 

        return query;

    }

any advise guys? thanks in advance

0

1 Answer 1

2

You need to build an expression tree:

var param = Expression.Parameter<Customer>();
p = Expression.LambdaFunc<Customer, bool>(
    Expression.Call(typeof(object), "Equals", null, //non-generic
                    Expression.Property(param, columnName),
                    Expresssion.Constant(value)
    )
);
Sign up to request clarification or add additional context in comments.

4 Comments

where is the == operator on that tree? how about expression for the .Contains method of a string.
@dot: Nowhere; It calls Object.Equals instead. This makes string equality work correctly (comparing by value). You can also build expression trees that call other methods; see the documentation.
uh, i get it, so when i want to use Contains(), ill just call typeof(string) and call the method "Contains" ? thanks
No; Contains is an instance method, so you call it on an instance rather than a type. Expression.Call(Expression.Property(param, columnName), "Contains", null, Expresssion.Constant(value))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.