2011-05-12 106 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