检查Linq查询中对象是否为空

4 .net c# linq

如何使用LINQ查询检查对象是否为空?

如果对象为空,我想从搜索中省略它.

我不想在查询之前执行If Else语句和重复代码并检查对象是否为Null.如果对象不为空,我的查询将返回错误"Nullable对象必须具有值".

public ActionResult Search(List<int> accountStatus = null , string accountName = "", int pageId = 1)
    {
        var model = Db.Entities
            .Where(i => i.GroupId == null && i.IsActive)
            .Where(an => string.IsNullOrEmpty(accountName) || (an.Name.StartsWith(accountName) || an.Name.Contains(accountName)))
            .ToList()
            .Where(accs => accountStatus == null || accountStatus.Contains((int)accs.CurrentStatusId.Value))
            .OrderByDescending(x => x.CreatedDate);    

        if (Request.IsAjaxRequest())
        {
            return PartialView("********", model.ToPagedList(pageId, nbItemsPerPage));
        }

        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 6

如果您想让所有的accs过程,当accountStatusnull,这样做:

.Where( accs => accs != null
                && ( accountStatus == null
                     || accountStatus.Contains(accs.CurrentStatusId.GetValueOrDefault(-1))
                   )
      )
Run Code Online (Sandbox Code Playgroud)