简体   繁体   中英

Lambda expression to create AND filter

I used this code to create a search filter.

I need is to pass an array of data and filter this data by AND.

Expression<Func<serveis, bool>> CombineWithAnd<T>(Expression<Func<T, bool>> firstExpression, Expression<Func<T, bool>> secondExpression)
{            
    var parameter = Expression.Parameter(typeof(T), "z");            
    var resultBody = Expression.AndAlso(Expression.Invoke(firstExpression, parameter), Expression.Invoke(secondExpression, parameter));

    return Expression.Lambda<Func<serveis, bool>>(resultBody, parameter);    
}

And then:

Expression<Func<T, bool>> resultExpression = n => false;     

foreach (var car in cars)
{    
    Expression<Func<T, bool>> expression = x => x.color_car.Any(z => z.car == car);
    resultExpression = CombineWithAnd(resultExpression, expression);
}

query = query.Where(resultExpression.Compile());

If I use this same code using OR or OrElse the search works correctly.

But I also need to perform the search by AND or AndAlso and it always returns zero results.

And I've checked in the database and there are both AND and OR results.

For AND, you should replace the starting "left side":

Expression<Func<T, bool>> resultExpression = n => false; 

with:

Expression<Func<T, bool>> resultExpression = n => true; 

because currently the left side fails your condition regardless of the right side

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM