使用列表中的值过滤linq查询结果

时间:2018-06-25 06:20:10

标签: c# linq

我正在尝试过滤查询结果jobs。我正在使用传递的List参数types尝试过滤jobstypes来自选中的多个复选框。问题是我在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,
    };
}

2 个答案:

答案 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()
    };