Reputation: 167
char[] delimiter = new char[] {' '};
string[] names = name.Trim().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
employees = (List<CMSUser>)employees.Where(
e =>
(e.FirstName.Contains(names[0]) && e.LastName.Contains(names[1])) ||
(e.LastName.Contains(name[0]) && e.FirstName.Contains(name[1]))
)
Above, I am trying to use Linq lambda to query employees List. I need to split the search term entered in input box for space character and use it to pull from employees list matching (FirstName && LastName) OR (LastName && FirstName) containing those two search words separated by space.
I don't know what I am doing wrong in query condition. It is returning all employees in list rather than giving those matching condition.
Upvotes: 1
Views: 2508
Reputation: 2531
Casting an IEnumerable returned by Where()
to a List should not work. Instead you can use ToList()
:
employees = employees.Where(
e =>
(e.FirstName.Contains(names[0]) && e.LastName.Contains(names[1])) ||
(e.LastName.Contains(names[0]) && e.FirstName.Contains(names[1]))
)
.ToList();
Upvotes: 0
Reputation: 2450
I think the problem happens in your second OR clause:
(e.LastName.Contains(name[0]) && e.FirstName.Contains(name[1])
It should be names
not name
, otherwise it gets the first and second characters respectively of the name
variable.
Upvotes: 3