2012-04-05 62 views
2

我有一個關於編寫linq查詢的常見做法的問題。其實我和我的同事吵了一架。Linq編碼風格:內聯如果

我們有一個布爾變量,如果它是真的 - 需要額外的檢查。如果它是錯誤的,則不應該有這樣的檢查。

有實現它在LINQ 2路:

bool onlyForReturningCustomers;  
.....  
return context.Products.Where(product => product.StartTime >= fromDate 
           && product.StartTime < toDate 
           && (onlyForReturningCustomers ? product.IsReturningClient : true)); 

與第二:

bool onlyForReturningCustomers; 
.....    
var q = context.Products.Where(product => product.StartTime >= fromDate && product.StartTime < toDate); 

if (onlyForReturningCustomers) { 
    q = q.Where(product => product.IsReturningClient); 
} 
return q; 

第一個呈現在SQL case聲明,當onlyForReturningCustomers=false1=1出現的語句,但該代碼被讀取更容易。

第二個不容易閱讀,但它在sql中顯示清晰的語句沒有任何垃圾。

你會使用哪一個?

+2

看起來你已經有了可用的工具/知識來回答這個問題。 – 2012-04-05 09:29:08

回答

3

我可能會去

bool onlyForReturningCustomers; 
.....    
// Make a positively-named variable 
bool includeAllCustomers = !onlyForReturningCustomers; 
var q = context.Products.Where(product => product.StartTime >= fromDate 
             && product.StartTime < toDate 
             && (includeAllCustomers 
              || product.IsReturningClient)); 

return q; 

這基本上是與您的第一種方式,但沒有條件表達式,其中一個分支只是說true的怪胎。

+0

你爲什麼不這樣做(!onlyForReturningCustomers || product.IsReturningClient)?保存使用變量:) – mattytommo 2012-04-05 09:39:02

+0

@mattytommo作爲一種風格的東西,我更喜歡布爾條件被表達/消費**積極**,我相信艾滋病的理解。我認爲Code Complete中有一些內容(對不起,現在不用它) – AakashM 2012-04-05 10:01:48

+0

啊夠公平,我會同意這個:)。 +1爲你的答案 – mattytommo 2012-04-05 10:05:10

0

我會使用第一個,因爲它看起來像第二個選項實際上是兩次往返數據。

我還要複製由LINQ聲明發出的SQL,將其粘貼到您最喜愛的SQL工具(如SQL Server Management Studio中),添加SET STATISTICS IO ON上述SELECT聲明並檢查邏輯讀取需要執行查詢(越低越好)。

+3

它不應該需要兩次往返:LINQ查詢通常被延遲,直到你真正要求結果。 – LukeH 2012-04-05 09:44:40

4

第二種說法更容易閱讀,並且如果您將來會爲返回客戶或其他類型的客戶添加業務規則,也更容易維護。