如何使用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)
如果您想让所有的accs
过程,当accountStatus
是null
,这样做:
.Where( accs => accs != null
&& ( accountStatus == null
|| accountStatus.Contains(accs.CurrentStatusId.GetValueOrDefault(-1))
)
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19515 次 |
最近记录: |