2011-05-12 73 views
0

我havea方法,返回式被用于基于客户需求记录的动态过滤,我在做的一个问题,我想是这样的动态的LINQ/LAMBDA过滤

 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; 

    } 

任何意见球员?在此先感谢

+0

任何人...... – dotnetlinc 2011-05-12 11:34:37

回答

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

哪里是那树上的==操作符?如何表达字符串的.Contains方法。 – dotnetlinc 2011-05-12 11:42:48

+0

@dot:无处;它调用'Object.Equals'来代替。这使得字符串相等性正确工作(按值比较)。您也可以构建调用其他方法的表达式树;请参阅文档。 – SLaks 2011-05-12 11:46:19

+0

恩,我明白了,所以当我想使用Contains(),生病只是调用typeof(字符串),并调用方法“包含”?谢谢 – dotnetlinc 2011-05-12 11:48:36