2013-03-08 126 views
7

我已經看過關於此stackoverflow,但無法找到我正在尋找的答案,其真正簡單。基本上我想知道如何檢查我的IEnumerable變量是否爲空,我的if語句只是嘲笑我並讓變量通過。mvc 4 IEnumerable檢查是否爲空

這裏是場景,我有一個從數據庫中提取的數據列表,這個小小的過濾器函數(因此沒有[HttpPost])根據用戶輸入過濾內容。它檢查的第一件事是審查數據庫中的審查列表,如果它返回空,我希望它檢查審查數據庫中的用戶列表。

下面的代碼:

var review = from m in _db.Reviews 
        select m;   

     if (!String.IsNullOrEmpty(searchString)) 
     { 
      review = review.Where(s => s.review.Contains(searchString)); 
      if (review != null && review.Any()) 
      { 
       return View(review);  
      } 
      else 
      { 
       review = review.Where(s => s.user.Contains(searchString)); 
       return View(review);  
      } 

我搞砸有關使用它了一下,if語句來檢查它是否爲空,然後.ANY(),然後= NULL,現在兩者變量只是繼續前進,大笑起來。我運行調試器並將其放在幾個位置上。當我輸入的是我知道的值不會返回任何結果,這是調試器說什麼檢討值:

「的IEnumerable沒有取得任何結果」

在一個可憐的企圖,以防止這一點,我甚至卡住那if語句中的句子。變化的笑聲如此強烈我發誓我可以通過我的揚聲器聽到它。

無論如何,如果我能得到最好的方式來做到這一點,爲什麼。會有餅乾。

+0

的if語句應該已經拿起變量爲空並且採取相應的行動,但它讓它通過:( – Jay 2013-03-08 16:29:32

回答

7

的問題是,當你這樣說:

  review = review.Where(s => s.user.Contains(searchString)); 

...你沒有修改原始查詢:

var review = from m in _db.Reviews 
       select m;   

反倒是,一個你在這裏創建:

 review = review.Where(s => s.review.Contains(searchString)); 

所以有效的你說:

如果查詢沒有任何結果,請爲其添加其他條件。

這顯然不會產生任何結果。

試試這個:

if (!String.IsNullOrEmpty(searchString)) 
    { 
     var reviewMatches = _db.Reviews.Where(s => s.review.Contains(searchString)); 
     if (reviewMatches.Any()) 
     { 
      return View(reviewMatches);  
     } 
     else 
     { 
      var userMatches = _db.Reviews.Where(s => s.user.Contains(searchString)); 
      return View(userMatches);  
     } 

請注意,您正在聲明的變量的方式,它是不可能對它們進行null,所以你只需要擔心是否是空的。

+0

啊這是非常合情合理的感謝!最簡單的東西總是被忽視 – Jay 2013-03-08 16:28:23

+2

不客氣,現在...我的餅乾在哪裏?;-) – StriplingWarrior 2013-03-08 16:49:11

+1

關於這個問題啊,有一個錯誤「Cookie無法找到」 – Jay 2013-03-08 17:02:44

0

嘗試對代替,如果條件:

var review = from m in _db.Reviews 
      select m;   

if (!String.IsNullOrEmpty(searchString)) 
{ 
    review = review.Where(s => s.review.Contains(searchString)); 
    if (review.count() != 0 && review.Any()) 
    { 
    return View(review); 
    } 
    else 
    { 
    review = review.Where(s => s.user.Contains(searchString)); 
    return View(review); 
    } 
    return null; 
}