Home > Net >  search function can not find user by name and surname
search function can not find user by name and surname

Time:09-17

When I search for a user by Name and Surname, for example, John Doe, I can't find the user. Even there is a user by that name and surname in DB. However, when I search just for NAME or Surname I will find the user. How can I fix this?

public List<User> SearchByName(string search)
{
    return _dBcontext.Users.Where(x => x.Name.Contains(search) || x.Surname.Contains(search)).ToList();
}

CodePudding user response:

When searching for "John Doe", your query is searching for records whose Name or Surname contain the entirety of "John Doe", e.g. "John".Contains("John Doe"). There are a few ways to resolve this, the two simplest that I can think of being:

  1. Split apart your search input into firstName and surname variables, and compare the variables to their respective record variables,
  2. use search.Contains(x.Name) || search.Contains(x.Surname)
  • Related