我正在为我正在处理的网络应用添加“搜索”功能,我有以下操作方法:
public PartialViewResult SearchEmployees(string search_employees)
{
var employeeList = _db.Employees.ToList();
var resultList = employeeList.Where(t => t.FirstName.Contains(search_employees)).ToList();
return PartialView(resultList)
}
这里我试图过滤掉所有具有包含搜索字符串的名字的员工,但是我一直在获取一个空列表。我使用lambda表达式错了吗?
另一个问题,是。包含区分大小写? (我知道在java theres .equals和.equalsIgnoreCase中,对于.Contains有类似的东西吗?)
答案 0 :(得分:4)
这里的问题是第一行中的.ToList()
。
.NET的string.Contains()
方法默认情况下区分大小写。但是,如果在LINQ-to-Entities查询中使用.Contains()
,Contains()
将遵循数据库的区分大小写(大多数数据库不区分大小写)。
当您在第一行调用.ToList()
时,它从数据库中删除了所有数据,因此第二行是执行普通的.NET .Contains()
。它不仅会给你带来意想不到的结果,而且性能也很糟糕,所以请在使用.ToList()
之前使用查询(如果你甚至使用.ToList()
全部)。
public PartialViewResult SearchEmployees(string search_employees)
{
var employeeList = _db.Employees;
var resultList = employeeList.Where(t => t.FirstName.Contains(search_employees))
.ToList();
return PartialView(resultList)
}
答案 1 :(得分:1)
您可以尝试以下代码吗?
public PartialViewResult SearchEmployees(string search_employees)
{
var employeeList = _db.Employees.ToList();
var resultList = employeeList;
if(!String.IsNullOrEmpty(search_employees))
resultList = employeeList.Where(t => t.FirstName.Contains(search_employees)).ToList();
return PartialView(resultList)
}
谢谢, 阿米特