如何重写此LINQ语句来处理位置变量条件?

时间:2017-04-06 02:03:59

标签: c# linq

public IQueryable<JobLevelsWithJobCountViewModel> JobLevelsWithJobCountViewModels(string location = null)
{
    return (from jl in _dbContext.JobLevels
            from j in jl.Jobs
            .Where(job => job.Company.ZipCode.MajorArea.Contains(location))
            .Where(job => !job.IsDeleted && !job.IsPrivate)
            group jl by jl.JobLevelId into g
            select new JobLevelsWithJobCountViewModel
            {
                JobLevel = g.FirstOrDefault(),
                JobCount = g.FirstOrDefault().Jobs.Count(j => !j.IsDeleted && !j.IsPrivate)
            });
}

我不想添加此条件。其中(job =&gt; job.Company.ZipCode.MajorArea.Contains(location))如果location为null

1 个答案:

答案 0 :(得分:0)

如果OR为空,请使用短路location运算符来传递条件:

.Where(job => location == null || job.Company.ZipCode.MajorArea.Contains(location))