简体   繁体   中英

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?

public IEnumerable<Result> Search(string searchText)
{
    if(string.IsNullOrEmpty(searchText))
        return _context.Person;
    else
        return _context.Person.Where(x => x.Contains(searchText));
}
_context.Person.Where(x => string.IsNullOrEmpty(searchText) ? true : x.Contains(searchText));
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));
    }

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.

而效率较低的方式......不确定这是否在语义上是正确的,但你明白了......

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

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.

I try all solutions and just below solution worked for me

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

Issues

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