如何使用LINQ查询检查对象是否为空?
如果对象为空,我想从搜索中忽略它。
我不想执行If Else语句和重复代码,并在查询之前检查对象是否为Null。目前,如果对象不为空,我的查询将返回错误“可为空的对象必须具有值”。
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);
}
如果您想让所有的accs
过程,当accountStatus
是null
,这样做:
.Where( accs => accs != null
&& ( accountStatus == null
|| accountStatus.Contains(accs.CurrentStatusId.GetValueOrDefault(-1))
)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句