LINQ - 如何忽略其中的空列表 [英] LINQ - How to ignore empty lists in where

查看:24
本文介绍了LINQ - 如何忽略其中的空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我使用 LINQ 的第一步.我有两个过滤器列表作为参数,它们也可以为空.如果我以这种方式执行代码,我不会从空列表中获取任何值.
如果要忽略空列表,代码应该是什么样的?

these are my first steps with LINQ. I have two lists for filters as parameters, which can also be empty. If I execute the code this way, I don't get any values back from an empty list.
What does the code have to look like if empty lists are to be ignored?

    public List<PersonDTO> GetPersons(int pageNumber, int pageSize, List<string> departments, List<string> locations, string filterText)
    {
        if (filterText == null)
        {
            filterText = "";
        }

        List<Person> personsList = _dbContext.Persons
            .Where(a => (a.firstName.ToLower().Contains(filterText.ToLower()) || a.lastName.ToLower().Contains(filterText.ToLower()))
                        && departments.Contains(a.department) 
                        && locations.Contains(a.location))
            .Skip(pageNumber * pageSize).Take(pageSize).ToList();

        return _mapper.Map<List<PersonDTO>>(personsList);
    }

推荐答案

不在查询中而是用if处理它们为空的情况:

Handle the case that they are empty not in the query but with if:

IEnumerable<Person> persons = _dbContext.Persons;
if(!string.IsNullOrEmpty(filterText))
{
    string lowerFilterText = filterText.ToLower();
    persons = persons
       .Where(p => p.firstName.ToLower().Contains(lowerFilterText) || a.lastName.ToLower().Contains(lowerFilterText));
}
if(departments.Any())
{
    persons = persons.Where(p => departments.Contains(p.department));
}
if(locations.Any())
{
    persons = persons.Where(p => locations.Contains(p.location));
}
List<Person> personList = persons.Skip(pageNumber * pageSize).Take(pageSize).ToList();

由于 LINQ 的延迟执行,这将仅在最终 ToList 处执行最终查询一次.

Due to LINQ's deferred execution this will execute the final query only once, at the final ToList.

这篇关于LINQ - 如何忽略其中的空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆