2016-03-22 56 views
0

我有一個查詢,它會給出結果集。基於我想寫where子句的條件。這意味着。我有一個變量x,如果x的值是「ALL」,那麼我不想添加這個條件。如果該值不是「ALL」,那麼我需要添加一個where子句(其中st.address = = X)。我如何在下面的查詢中添加這個條件。如何在單個linq查詢中給出條件where子句?

var abc=(from st in Context.STopics join ap in Context.ATopic on st.id equals ap.id 
where st.address==x 
select new result() 
{ 
name = st.name 
add= ap.add}).ToList(); 
+0

這不是重複。 – poc

+0

_「這不是重複的」_ - 五個用戶不同意你的意見。我同意他們。你爲什麼認爲它不是? – CodeCaster

回答

3

這裏是你在找什麼:

var yourQuery = Context.STopics.AsQueryable(); 
var yourParam = "ALL"; 
if(yourParam != "ALL") 
    yourQuery = yourQuery.Where(x => x.IsActive==true && x.StudentID == 123); 

var abc = yourQuery.Select(x=> new result() 
           { 
            name = st.name 
           }).ToList(); 

的事情是,與LINQ你沒有從查詢中獲取數據的時候了。因此,您可以根據需要以這種方式構建您的實際查詢。

+0

@CodeCaster我的不好 –

1

你可以讓你的條件的所有元素相匹配時x = "ALL"否則匹配您的其他條件的方式:

var abc=(from st in Context.STopics 
where x == "ALL" || (st.IsActive==true && st.StudentID == 123) 
select new result() 
{ 
name = st.name }).ToList(); 
+2

我想我已經問了幾次之前,但_please_添加一些解釋給你的答案,而不是傾銷「固定」的代碼。如果可以阻止,您也不希望在數據庫上執行此查詢。它會變成'WHERE'ALL'='ALL'',這可以通過任何一種方式在客戶端完成。 – CodeCaster

+0

@CodeCaster現在更好嗎? –

+0

是的,謝謝。它有助於後來的讀者看到你做了什麼。 – CodeCaster

0

喜歡的東西:

var abc=(from st in Context.STopics 
where (x!="All" ? (st.IsActive==true && st.StudentID == 123)) 
select new result() 
{ 
    name = st.name 
}).ToList();