Search code examples
c#linqentity-frameworkentity-framework-4

Linq Query with Contains and Nullable Value


I have a method for searching which looks like this:

public IEnumerable<Result> Search(string searchText)
{

     return _context.Person.Where(x => x.Contains(searchText));
}

I want to be able to call this function with searchText being null/empty and get all of the records back.

I have tried this with no luck:

return _context.Person.Where(x => x.Contains(searchText ?? ""));

is there another way to accomplish this besides breaking it up into two steps and checking searchString in an if statement before applying it to the query?


Solution

  • public IEnumerable<Result> Search(string searchText)
    {
        if(string.IsNullOrEmpty(searchText))
            return _context.Person;
        else
            return _context.Person.Where(x => x.Contains(searchText));
    }