如何使用LINQ查询检查对象是否为空?
如果对象为空,我希望在搜索中省略它。
我不想做一个If Else语句并复制代码,在查询之前检查对象是否为空。目前,如果对象不为空,我的查询将返回错误"可空对象必须具有值。"
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);
}
ToList
? - Patrick Hofman.Where(accs => accountStatus == null || accountStatus.Contains((int)accs.CurrentStatusId.Value))
- user4884237accountStatus
是null
。 - user4884237accountStatus
是否为空 (==null
)?难道你不想确保它 不是空 吗? - Yuval Itzchakov