stephen776
stephen776

Reputation: 9234

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?

Upvotes: 6

Views: 11707

Answers (7)

mohammad hasani
mohammad hasani

Reputation: 71

I try all solutions and just below solution worked for me

query = query.Where(e =>  e.CategoryType.HasValue && categoryTypes.Contains(e.CategoryType.Value));

Issues

Upvotes: 7

Diego
Diego

Reputation: 20194

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

Upvotes: 5

Slauma
Slauma

Reputation: 177133

Assuming that Person is a class Contains seems to be method of this class. An expression like Where(x => x.Contains(searchText)) or Where(x => string.IsNullOrEmpty(searchText) || x.Contains(searchText)) where x is a Person won't work at all with LINQ to Entities, even with a simple class like ...

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool Contains(string searchText)
    {
        return Name.Contains(searchText);
    }
}

... it will throw an exception because LINQ to Entities can't translate this method to a storage expression. Where(x => string.IsNullOrEmpty(searchText) || x.Name.Contains(searchText)) would work though.

Upvotes: 0

Bala R
Bala R

Reputation: 108937

return _context.Person.Where(x =>string.IsNullOrEmpty(searchText) ? true : x.Contains(searchText));

or

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

Upvotes: 0

gt124
gt124

Reputation: 1258

And a less efficient way... Not sure if this is semantically correct but you get the idea...

return _context.Person.Where((x, index) => x.Contains(searchText ?? x[index]));

Upvotes: 0

Mikael &#214;stberg
Mikael &#214;stberg

Reputation: 17146

You can do it like this:

return _context.Person.Where(x => 
   string.IsNullOrEmpty(searchText) || 
   x.Contains(searchText)
);

This is a pattern I use a lot when I have parameters I want to apply only if they are set.

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 99957

_context.Person.Where(x => string.IsNullOrEmpty(searchText) ? true : x.Contains(searchText));

Upvotes: 8

Related Questions