2012-12-21 56 views
1

我有一個Linq查詢,有時在兩個數據集上加入,而在其他時間加入三個。沒有從第三組返回的數據,它僅用於基於其內容過濾數據。我使用Predicate Builder來動態創建wheres,但我不確定動態包含/排除連接的數據集的正確方法。動態添加聯接到linq查詢的技巧?

有時候這樣的:

var filteredResults = from d in dateRangeResults 
           join n in results on d.ID equals n.ID         
           select new { name = n, demo = d }; 

而其他時候,我需要這樣的:

var filteredResults = from d in dateRangeResults 
           join n in results on d.ID equals n.ID 
           join p in PnSIncludeResults on n.ID equals p 
           select new { name = n, demo = d }; 

是否有一個最佳實踐或技術? TIA

回答

3

對於性能,我會在if語句中添加額外連接。這將在兩種情況下,建立一個高效的查詢:

var filteredResults = from d in dateRangeResults 
         join n in results on d.ID equals n.ID 
         select new { name = n, demo = d }; 

if(filterExtra) 
{ 
    filteredResults = from result in filteredResults 
         join p in PnSIncludeResults on result.name.ID equals p 
         select result; 
} 

如果你更關心的可讀性,您可以使用where條款,而不是join條款:

var filteredResults = from d in dateRangeResults 
         join n in results on d.ID equals n.ID 
         where !filterExtra || PnSIncludeResults.Contains(n.ID) 
         select new { name = n, demo = d }; 

LINQ到實體可能優化結果查詢,但你應該檢查確定。

+0

+1舊版SQL內部JOIN過濾。 – Aron