【问题标题】:mvc 4 IEnumerable checking if its nullmvc 4 IEnumerable 检查其是否为空
【发布时间】:2013-03-08 16:14:11
【问题描述】:

我已经在 stackoverflow 上寻找过这个,但找不到我正在寻找的答案,它真的很简单。基本上我想知道如何检查我的 IEnumerable 变量是否为空,我的 if 语句只是嘲笑我并让变量通过。

这是场景,我有一个从数据库中提取的数据列表,这一点是一个过滤功能(所以没有 [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 语句用于检查它是否为 null,然后是 .any(),然后是 != null,现在两者都是,变量只是走过去,边走边笑。我运行调试器并将其放在几个位置。当我输入一个我知道不会返回结果的值时,这就是调试器所说的审查值:

“IEnumerable 没有产生任何结果”

为了防止这种情况发生,我什至在 if 语句中删掉了那句话。这个变量笑得很厉害,我发誓我可以通过我的扬声器听到它。

无论如何,伙计们,如果我能找到最好的方法来做到这一点,以及为什么。会有cookies。

【问题讨论】:

  • if 语句应该将变量设为 null 并采取相应的行动,但它让它通过了 :(

标签: c# asp.net-mvc linq asp.net-mvc-4


【解决方案1】:

问题是当你这样说时:

         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,所以你只需要担心它们是否为空。

【讨论】:

  • 啊,这很有道理!非常感谢您的解释。最简单的事情总是被忽视
【解决方案2】:

用 if 条件试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2017-04-21
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多