Mvc 4 IEnumerable check if its null

I looked at stackoverflow for this, but can't find the answer I'm looking for, its simple really. Basically I want to know how to check if my IEnumerable variable is null, the if statement just laughs at me and skips the variables.

Here's the scenario, I have a list of data retrieved from the database, this little bit is a filter function (so there is no [HttpPost]) that filters content based on user input. The first thing he checks is the overview list in the overview database, if it returns empty, I want him to check the list of users in the overview database.

here is the code:

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); } 

I messed up this a bit, the if statement used to check if it was null, then .any (), then! = Null and now both of them, the variable just goes, laughing when it goes. I started the debugger and put it on a few points. When I enter a value that I know will not return results, this is what the debugger says the review value is:

"IEnumerable gave no results"

In a miserable attempt to prevent this, I even threw this sentence into an if statement. the variable laughed so hard that I swear I heard it through my speakers.

Anyway guys if I could get a better way to do this and why. There will be cookies.

+7
source share
2 answers

The problem is that when you say this:

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

... you do not change the original request:

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

But rather, the one you create here:

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

So effectively you say:

If the query has no results, add additional criteria to it.

This, obviously, will also not produce any results.

Try this instead:

  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); } 

Note that the way you declare your variables cannot be null , so you only need to worry about whether they are empty.

+7
source

Try this instead of the if condition:

 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; } 
0
source

All Articles