动态Linq / Lambda过滤

时间:2011-05-12 11:26:43

标签: c# linq lambda

我有一个返回Expression的方法,用于根据客户需求动态过滤记录,我有一个问题,我想要这样的东西

     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;

    }

任何建议家伙?提前谢谢

1 个答案:

答案 0 :(得分:2)

您需要构建表达式树:

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