简体   繁体   中英

Linq query with where conditions (x && x) || (x & x)

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.

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM