PredicateBuilder类(linq多条件组合查询)

 public static class PredicateBuilder

    {



        /// <summary>

        /// 机关函数应用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混应时写在AND后的OR有效  

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <returns></returns>

        public static Expression<Func<T, bool>> True<T>() { return f => true; }



        /// <summary>

        /// 机关函数应用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混应时写在OR后面的AND有效  

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <returns></returns>

        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);

        } 

    }
            var p = PredicateBuilder.True<Table_1>();//声明PredicateBuilder一个PredicateBuilder类型

            p = p.And(s => s.id > 4);

            p = p.And(s => s.id < 9);//把查询条件,合并起来

            var db = new DataClasses3DataContext();

            var a = db.Table_1s.AsQueryable();

            GridView1.DataSource = a.Where(p).Select(b=>b); //通过调用P,调用查询条件,这样就可以把查询条件动态的组合起来 

            GridView1.DataBind();

运行结果:

id name
5 456      
6 567      
7 123      
8 78789    

你可能感兴趣的:(builder)