Search code examples
c#asp.net-mvclinqpredicatebuilderlinqkit

How to check if predicate expression was changed?


 var predicate = PredicateBuilder.True<o_order>();

This is my predicate expression, where on some certain conditions I will append expressions with it.

Likewise

 if (!string.IsNullOrEmpty(param.sSearch))
                predicate = predicate.And(s => s.OrderID.ToString().Contains(param.sSearch));

Now my question is if this expression doesn't pass by this condition then would there be any expression? and how would I know if it returns no expression with it.

Simply I want to do-

if(predicate==null) or if(predicate contains no expression)


Solution

  • This is so easy, you probably didn't consider that. Since PredicateBuilder builds new predicate instances each time (notice that you must write predicate = predicate.And... so you are replacing the pred each time), then you can simply just remember the original value and eventually compare the final value against that.

    var predicate = PredicateBuilder.True<o_order>();
    var oldPredicate = predicate;
    
    if (!string.IsNullOrEmpty(param.sSearch))
        predicate = predicate.And(s => ........... );  // replace!
    
    if (!string.IsNullOrEmpty(....))
        predicate = predicate.And(s => ........... );  // replace!
    
    if(predicate == oldPredicate)   // was it changed?
        ; // no filters applied
    else
        ; // some filters applied
    

    It'd be hard however to tell which filters were applied. If you need to know that, then you must store the information alongside (or you have to analyze the predicate tree, which can be harder):

    var predicate = PredicateBuilder.True<o_order>();
    var oldPredicate = predicate;
    
    bool case1applied = !string.IsNullOrEmpty(....);
    if (case1applied)
        predicate = predicate.And(s => ........... );
    
    bool case2applied = !string.IsNullOrEmpty(....);
    if (case2applied)
        predicate = predicate.And(s => ........... );
    
    if(predicate == oldPredicate) // or the hard way: !case1applied && !case2applied
        ; // no filters applied
    else
        if(case1applied && case2applied) // all filters applied
        else ....