很多时候,我们的查询条件有多个,并且参数不一样,得到的查询条件也就不一样。这就要我们动态的生成查询条件,再把这些查询条件合并起来。网上找了这个类,可以很好的达到我们的要求。
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); } }
测试一下:
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"); //返回字长大于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); //合并两个条件:返回字长大于3且包括o字符 results = list.Where(exp3.Compile()); foreach (var result in results) { Console.WriteLine(result); } Console.Read(); }