首页 > 解决方案 > 检查参数值是否在查询中为空

问题描述

在我的查询中,我基于RoleIdand获取记录LocationId,有时用户可能不会传递位置,在这种情况下我想删除该过滤器并从所有位置获取信息。

目前我正在这样做

if(loc > 0)
{
    var myResult = (from x in CSDB.Allocations
                   join s in CSDB.Managers
                   on x.ManagerId equals s.Id
                   Where x.RoleId == 2 && s.LocationId == loc
                   select new
                   {
                    x.name,
                    x.Date
                   }).ToList();
}
else
{
    var myResult = (from x in CSDB.Allocations
                   join s in CSDB.Managers
                   on x.ManagerId equals s.Id
                   Where x.RoleId == 2 
                   select new
                   {
                    x.name,
                    x.Date
                   }).ToList();
}

我正在查看是否可以检查查询中是否loc为空,而不是使用 if else。

标签: c#.netlinq

解决方案


你可以这样做:

Where x.RoleId == 2 && (loc == null || s.LocationId == loc)

推荐阅读