Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a dynamic AND OR linq expression tree in a loop

Tags:

c#

linq

Following on from a previous question i asked, I'm now trying to figure out how to build dynamic expressions for both AND & OR queries.

Given the following string array:

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

I would like to dynamically express this in a linq expression - Something along the lines of:

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 do i dynamically build the 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?
}
like image 946
Fixer Avatar asked Mar 15 '12 14:03

Fixer


People also ask

Can you use LINQ on dynamic?

It's possible to build up dynamic LINQ queries or queries with several conditional criteria. In fact there are several options for doing this, including the use of expression trees.

Can we use dynamic in lambda expression?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.

What is Dynamic LINQ?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.


1 Answers

Use 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 boolean state of false, and or together predicates in the loop. Conversely, you can start with a state of true and and together the predicates.

Finally, not sure if this is possible with query comprehension syntax, but your ultimate query can then look like:

var v = products.Where(predicate);
like image 194
Kirk Woll Avatar answered Nov 03 '22 21:11

Kirk Woll