Global Ryan Studio(工作室)

最好最实用的软件开发和提供者

条件Lamada树生成器

    /// <summary>
    /// 条件表达式生成器
    /// </summary>
    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);
        }
    }
       /// <summary>
       /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSearch_Click(object sender, EventArgs e)
        {


            Expression<Func<Company, bool>> expr = Select();
            var source = from c in db.Company.Where(expr)
                         select c;
            rptSupplier.DataSource = source.Skip(anpPage.PageSize * (anpPage.CurrentPageIndex - 1)).Take(anpPage.PageSize); ;
            rptSupplier.DataBind();
            anpPage.RecordCount = source.Count();


        }
        /// <summary>
        /// 获取多条件查询树
         /// </summary>
        /// <returns></returns>
        public Expression<Func<Company, bool>> Select()
        {
            var predicate = PredicateBuilder.True<Company>();
            if (!string.IsNullOrEmpty(txtComanyName.Text))
            {
                predicate = predicate.And(p => p.CompanyName.Contains(txtComanyName.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtContactName.Text))
            {
                predicate = predicate.And(p => p.ContactName.Contains(txtContactName.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtContactTitle.Text))
            {
                predicate = predicate.And(p => p.ContactTitle.Contains(txtContactTitle.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtCity.Text))
            {
                predicate = predicate.And(p => p.City.Contains(txtCity.Text.Trim()));
            }
            return predicate;
        }


阅读更多
文章标签: object class c
个人分类: Linq
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭