我正在尝试过滤查询结果jobs
。我正在使用传递的List参数types
尝试过滤jobs
。 types
来自选中的多个复选框。问题是我在foreach (var type in types)
处得到了乔布斯结果错误。我只得到foreach
中最后一项的结果。
public JobsOutPut GetJobs(List<string> types, string country)
{
//Getting the jobs here
var jobs =
(
from row in _jobCategoryRepository.GetAll().ToList()
join rowT in _jobTypeRepository.GetAll().ToList()
on row.JobId equals rowT.JobId
orderby row.CreationTime descending
select new JobDto
{
Id = row.JobId,
Title = row.Job.Title,
}
)
.AsEnumerable()
.Where(j => j.Country.Contains(country));
if (types.Any())//if that List has stuff filter jobs using those values.
{
//is there a better approach leading to correct results?I ran out of ideas
foreach (var type in types)
{
jobs = jobs.Where(j => j.TypeName == type);
}
}
var fJobs = jobs.ToList();
return new FilterJobOutPut
{
JobsList = fJobs,
};
}
答案 0 :(得分:3)
使用Contains()
使您的代码更简单,只需确保j.TypeName
的大小写和types
的内容应该相同
if (types.count >0)
{
return new FilterJobOutPut
{
JobsList = jobs.Where(j => types.Contains(j.TypeName)).ToList()
};
}
else
return null //make null check where ever you call this method else use new FilterJobOutPut()
答案 1 :(得分:2)
在我看来您想要这个:
public JobsOutPut GetJobs(List<string> types, string country)
{
//Getting the jobs here
var jobs =
(
from row in _jobCategoryRepository.GetAll().ToList()
join rowT in _jobTypeRepository.GetAll().ToList() on row.JobId equals rowT.JobId
let jobDto = new JobDto
{
Id = row.JobId,
Title = row.Job.Title,
}
where jobDto.Country.Contains(country)
where !types.Any() || types.Any(t => jobDto.TypeName == t)
orderby row.CreationTime descending
select jobDto
);
return new FilterJobOutPut
{
JobsList = jobs.ToList(),
};
}
或者,如果您想获得更多幻想,可以这样做:
public JobsOutPut GetJobs(List<string> types, string country) =>
new FilterJobOutPut
{
JobsList =
(
from row in _jobCategoryRepository.GetAll().ToList()
join rowT in _jobTypeRepository.GetAll().ToList() on row.JobId equals rowT.JobId
let jobDto = new JobDto
{
Id = row.JobId,
Title = row.Job.Title,
}
where jobDto.Country.Contains(country)
where !types.Any() || types.Any(t => jobDto.TypeName == t)
orderby row.CreationTime descending
select jobDto
).ToList()
};