2014-03-06 64 views
0

我得到了這個linq查詢,它使用下拉菜單搜索我的數據庫中的選定值。隱藏加入如果string.IsNullOrEmpty使用Linq

如果ddlCategory爲空,有沒有辦法在linq查詢中隱藏「連接」?我想這是因爲搜索結果顯示重複行,因爲我的文檔可以有很多類別。希望你明白我的意思..任何人都可以幫忙嗎?

var documents = from d in data.tblDocuments 

      join sc in data.tblSubCategories on d.DocId equals sc.DocId 
      orderby d.Docyear descending 

      where 
       (string.IsNullOrEmpty(person) || d.DocPerson.Equals(person)) && 
       (string.IsNullOrEmpty(year) || d.Docyear.Equals(year)) && 
       (string.IsNullOrEmpty(law) || d.DocLaw.Equals(law)) && 
       (string.IsNullOrEmpty(court) || d.DocCourt.Equals(court)) && 
       (string.IsNullOrEmpty(category) || sc.CategoryId.Equals(category)) && 
       (string.IsNullOrEmpty(casenr) || d.DocNr.Equals(casenr)) 

      select d; 
+0

您也有通過'這裏sc'濾波 –

回答

0

使用lambda語法:

var query = data.tblDocuments; 

if (condition) // conditionally add join 
    query = query.Join(data.tblSubCategories.Where(sc => sc.CategoryId == category), 
         d => d.DocId, sc => sc.DocId, (d,sc) => d); 

// continue to compose query 
query = query.OrderByDescending(d => d.Docyear) 
      .Where(d => ...); 

順便說一句,你可以根據條件篩選組成:

if (!String.IsNullOrEmpty(person)) 
    query = query.Where(d => d.DocPerson == person);