How to build a dynamic tree of OR or linq expressions in a loop

Following the previous question, I asked: now I'm trying to figure out how to create dynamic expressions for AND and OR queries.

Given the following array of strings:

string[] ranges = new string[]{"0-100", "100-200", "500-1000"}; 

I would like to dynamically express this in a linq expression - Something line by line:

 var v = from p in products where (p.Amount >= 0 && p.Amount <= 100) || (p.Amount >= 101 && p.Amount <= 200) || (p.Amount >= 500 && p.Amount <= 1000) select p; 

How to dynamically build linq expression in this loop?

 string[] ranges = new string[]{"0-100", "100-200", "500-1000"}; var query = products.AsQueryable(); foreach (var item in ranges) { int min = int.Parse(item.Split('-').First()); int max = int.Parse(item.Split('-').Last()); //Linq expression? } 
+8
c # linq
source share
1 answer

Use the predicate builder :

 string[] ranges = new string[]{"0-100", "100-200", "500-1000"}; var predicate = PredicateBuilder.False<Product>(); foreach (var item in ranges) { int min = int.Parse(item.Split('-').First()); int max = int.Parse(item.Split('-').Last()); predicate = predicate.Or(p => p.Amount >= min && p.Amount <= max); } 

Notice how we start with the logical state false , and or together the predicates in the loop. Conversely, you can start with true and and with predicates.

Finally, I'm not sure if this is possible with the syntax for understanding the request, but your final request may look like this:

 var v = products.Where(predicate); 
+16
source share

All Articles