Reputation: 10021
I'm adding a "search" functionality to a web app I'm working on and I have the following action method:
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)
}
here I'm trying to filter out all employees that have a first name that contains the search string, however I keep getting a null list. Am I using the lambda expression wrong?
another question, is .Contains case sensitive? (I know in java theres .equals and .equalsIgnoreCase, is there something similar to this for .Contains?)
Upvotes: 0
Views: 8002
Reputation: 101738
The problem here was the .ToList()
in the first line.
.NET's string.Contains()
method is, by default, case sensitive. However, if you use .Contains()
in a LINQ-to-Entities query, Contains()
will follow the case sensitivity of the database (most databases are case insensitive).
When you called .ToList()
in the first line, it pulled down all of your data from the database, so the second line was doing an ordinary .NET .Contains()
. Not only did it give you unexpected results, it's also terrible for performance, so please make a point to use a query before you use .ToList()
(if you even use .ToList()
at all).
public PartialViewResult SearchEmployees(string search_employees)
{
var employeeList = _db.Employees;
var resultList = employeeList.Where(t => t.FirstName.Contains(search_employees))
.ToList();
return PartialView(resultList)
}
Upvotes: 4
Reputation: 1190
Can you try the following code?
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)
}
Thanks, Amit
Upvotes: 1