2012-02-09 85 views
1

我有這樣的方法結合Lambda表達式

public Expression<Func<Auction, bool>> GetUnsetDatesAuctionsExpression() 
     { 
      if (condition) 
       return GetAllUnsetDatesAuctionsExpression(); 
      else 
       return (a => 
         (membershipUser.ProviderUserKey != null) && 
         (a.OwnerReference == (Guid)membershipUser.ProviderUserKey) && 
         ((a.Starts == null) || (a.Ends == null))); 
      } 
     } 

調用該方法

private Expression<Func<Auction, bool>> GetAllUnsetDatesAuctionsExpression() 
     { 
      return (a => (a.Starts == null) || (a.Ends == null)); 
     } 

的問題是,在上述公開方法我有以下線

(a.Starts == null) || (a.Ends == null) 

這與私有方法中表達式的主體相同。現在

,這樣做,當然,不工作,因爲你不能和一個布爾值和表達

return (a => 
    (membershipUser.ProviderUserKey != null) && 
    (a.OwnerReference == (Guid)membershipUser.ProviderUserKey) && 
    (GetAllUnsetDatesAuctionsExpression)); 

所以,問題是,我怎麼呼叫相結合,與私有方法

(membershipUser.ProviderUserKey != null) && 
    (a.OwnerReference == (Guid)membershipUser.ProviderUserKey) 
+0

您是否嘗試過(GetAllUnsetDatesAuctionsExpression)(一)? – 2012-02-09 11:50:31

回答

3

創建一個新的表達式作爲兩者的結合,看到BinaryExpression

System.Linq.Expressions.BinaryExpression binaryExpression = 
    System.Linq.Expressions.Expression.MakeBinary(
    System.Linq.Expressions.ExpressionType.AndAlso, 
    firstExpression, 
    secondExpression); 
+0

問題是我的公共方法GetUnsetDatesAuctionsExpression返回一個表達式不是BinaryExpresssion。 – 2012-02-09 13:05:35

+0

@Sachin - BinaryExpression仍然是一個表達式。 – 2012-02-09 13:57:21

0

你能不能改變它的這個表達式:

return (a => (a.Starts == null || a.Ends == null)); 
1

試試下面的(我取出超fluous括號內):

return a => 
    membershipUser.ProviderUserKey != null && 
    a.OwnerReference == (Guid)membershipUser.ProviderUserKey && 
    GetAllUnsetDatesAuctionsExpression().Compile()(a); 
    // ---------------------------------^^^^^^^^^^^^^ 

上面的代碼使用Expression.Compile方法來編譯由表達式樹描述的λ表達式(由GetAllUnsetDatesAuctionsExpression()方法)成可執行代碼返回併產生表示lambda表達式的委託。

編輯:我沒有注意到你的公共方法返回一個表達式,而不是一個值。當然,在你的場景中Hans Kesting's approach要好得多。