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

前端 未结 1 820
粉色の甜心
粉色の甜心 2021-02-08 00:26

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 a

1条回答
  •  清酒与你
    2021-02-08 01:08

    Use predicate builder:

    string[] ranges = new string[]{"0-100", "100-200", "500-1000"};
    var predicate = PredicateBuilder.False();
    
    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);
    

    0 讨论(0)
提交回复
热议问题