Most of the time, we have multiple query conditions, and the parameters are different, so the query conditions are different. In this case, we need to dynamically generate query conditions and then combine these query conditions. I found this category online, which can meet our requirements.
public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T>() { return f => true; } public static Expression<Func<T, bool>> False<T>() { return f => false; } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, bool>> (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters); } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, bool>> (Expression.And(expr1.Body, invokedExpr), expr1.Parameters); } }
Test:
Static void LinqAndTest () {List <string> list = new List <string> (); list. add ("one"); list. add ("two"); list. add ("three"); list. add ("four"); list. add ("five"); list. add ("six"); // The returned word length is greater than 3 Expression <Func <string, bool> exp = s => s. length> 3; var results = list. where (exp. compile (); foreach (var result in results) {Console. writeLine (result);} Expression <Func <string, bool> exp2 = s => s. contains ('O'); var exp3 = exp. and (exp2); // merge two conditions: the returned word is greater than 3 And contains the o character results = list. where (exp3.Compile (); foreach (var result in results) {Console. writeLine (result);} Console. read ();}