2013-04-12 75 views
0

我正在學習LINQ to sql的過程。如果LINQ中有其他條件

是否有可能在LINQ to SQL中寫入以下條件?

條件1

var query1 = 
      if 
      from q in db.Students 
      q.fees =="paid" && q.activites == "good" && count == 0 
      select q 

       save "OK" to the property result. 

      else 
      from q in db.Students 
      q.fees =="paid" && q.activites == "good" && count == 2 
      select q 
      save "better" to the property result. 

      else 
      from q in db.Students 
      q.fees =="paid" && q.activites == "good" && count > 2 
      select q 
      save "bad" to the property result. 


    private string _result; 
    public string Result 
    { 
     get { return this._result; ; } 
     set { this._result; = value; } 
    } 

麻煩引導。

更新編輯:

var query1 =     
      (from q in db.Students 
      q.fees =="paid" && q.activites == "good" 
      select q).Any(); 

    if(count ==0 && query1 == true) 
    { 
    this.Result = "OK" 
    } 
    esle if(count == 2 && query1 == true) 
    { 
    this.Result = "better" 
    } 
    esle 
    { 
    this.Result = "bad" 
    } 

這將是一個辦法?

+2

http://stackoverflow.com/questions/15909926/linq-if-else-condition/15909991#_=_看到 –

+3

因爲這是代碼的一面,爲什麼不使用常規的如 - else模式並將必要的linq查詢放入這些塊中? – valverij

+0

可以請你舉一個例子 – user1221765

回答

1

因爲這是所有代碼端,你可以用你運行你的LINQ查詢後,使用普通的if-else模式。

實施例:

var query1 =     
     from q in db.Students 
     q.fees =="paid" && q.activites == "good" 
     select q; 

if(count ==0 && query1.Count() > 0) 
{ 
    this.Result = "OK"; 
} 
else if(count == 2 && query1.Count() > 0) 
{ 
    this.Result = "better"; 
} 
else 
{ 
    this.Result = "bad"; 
}  

由於LINQ只是被用來確定記錄是否存在,不過,我建議使用的.Any()方法。

var recordsFound = db.Students.Any(q => q.fees =="paid" && q.activites == "good"); 

if(count == 0 && recordsFound) 
{ 
    this.Result = "OK"; 
} 
else if(count == 2 && recordsFound) 
{ 
    this.Result = "better"; 
} 
else 
{ 
    this.Result = "bad"; 
} 
+0

我會盡力回覆,感謝更新@valverij – user1221765

+0

你能解釋一下count()> 0在這裏是第一個解決方案嗎? – user1221765

+0

因爲query1的類型是'Enumerable ',所以'.Count()'只返回集合中包含的元素的數量。如果這不是你的意圖,那麼讓我知道,我可以更新答案。 – valverij

0

它看起來像你總是在相同的條件下查詢,而你有條件地做出的唯一反應就是返回結果的數量。你可以用where條件得到結果,然後在結果計數週圍放一個if語句。

var count = (from q in db.Students 
where q.fees == "paid" && q.activities == "good" 
select q).Count(); 

if(count == 0){ 
    //do something 
} 
else if(count == 2){ 
    //do something 
} 
///etc... 
+0

請參閱我的上述評論,我已經嘗試過這一點,它與計數工作正常。比較count和query1時我遇到了問題。 – user1221765