mvc 4 IEnumerable checking if its null
asp.net-mvc, asp.net-mvc-4, c#, linq
Solution
The problem is that when you say this:
review = review.Where(s => s.user.Contains(searchString));
... you're not modifying the original query:
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're saying:
If the query doesn't have any results, add additional criteria to it.
This will obviously not yield any results either.
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're declaring your variables, it's impossible for them to be `null`, so you only have to worry about whether they are empty.
Problem
I've looked about on 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, my if statement just laughs at me and lets the variables pass. Here's the scenario, I have a list of data pulled from the database, this little bit is a filter function (so no [HttpPost]) that filters the content based on user input. The first thing it checks is the review list in the review database, if this returns empty I want it to check the user list in the review database. here's 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've messed about with it a bit, the if statement used to check if it was null, then .any(), then != null and now both, the variable just walks on by, laughing as it goes. I ran debugger and put it on a few spots. When I input a value that I know will not return results this is what the debugger says the review value is: "IEnumerable did not yield any results" In a pathetic attempt to prevent this I even chucked that sentence in the if statement. the variable laughed so hard I swear I could hear it through my speakers. Anyways guys, if I could get the best way to do this, and why. There will be cookies.