1. 程式人生 > 其它 >Expression多條件篩選

Expression多條件篩選

使用場景:多條件篩選,不確定條件的個數時,可選擇此種方式;

擴充套件類:

 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