使用场景:多条件筛选,不确定条件的个数时,可选择此种方式;
扩展类:
public static class ExpLinqExpressions { 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); } }
使用样例:
#region 多条件筛选 ///查询数据库的仓储类 ItestRepository test = new TestRepository(); test.FindAll(d => d.Id == 1); Expression<Func<Test, bool>> pre; pre = s => s.Id == 1; int money = 10; if (money > 0) { pre = pre.And(d => d.Money == money); } var vlus = test.FindAll(pre.Compile()); #endregion