关闭

条件Lamada树生成器

930人阅读 评论(0) 收藏 举报
    /// <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;
        }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:99157次
    • 积分:1342
    • 等级:
    • 排名:千里之外
    • 原创:38篇
    • 转载:13篇
    • 译文:0篇
    • 评论:16条
    文章分类
    最新评论