LINQ PredicateBuilder a few ORs starting with PredicateBuilder.True <>

I have an object like this:

 public class Product() { public string Name { get; set; } } 

I want to implement a keyword search in the Name property so that they are OR'ed. In other words, the search:

knife fork with spoon

will look for a spoon or knife or in the Name property. I introduced a new method for PredicateBuilder in Product , which looks like this:

 public static Expression<Func<Product, bool>> ContainsKeywords(params string[] keywords) { var predicate = PredicateBuilder.True<Product>(); foreach (var keyword in keywords) { var temp = keyword; predicate = predicate.Or(x => x.Name.Contains(temp)); } return predicate; } 

And I use it as one of my methods for a web service:

 var keywords = Request.QueryString["q"].Split(' '); var products = Repo.GetAll<Product>(); // get all the products from the DB products = products.Where(Product.ContainsKeywords(keywords)); 

The problem I am facing is that the user may not perform a search on keywords, in which case the keywords array will be empty. If I start with PredicateBuilder.True<Product>() , I get a list of all Products , no matter what keywords I insert. If I start with PredicateBuilder.False<Product>() , it works if the user enters keywords, but if not, then the return list is empty because everything matches false .

How to fix this to get the desired behavior, which should return a list of all Products if a keyword was not provided, and return a list of only Products that matches the keywords if they were provided? I know that I can check to see if the array of keywords is empty before I do any processing, but if at all possible, I would like PredicateBuilder handle this case automatically.

+4
source share
1 answer
 var predicate = (keywords.Count() > 0) ? PredicateBuilder.False<Product>() : PredicateBuilder.True<Product>(); 
+2
source

Source: https://habr.com/ru/post/1338034/


All Articles