LINQ 多条件查询 where 条件组建

1.新建一个静态类

    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);
        }
    }
2.条件建立和调用

                Expression<Func<View_UserAndRole, bool>> ExpWhere = PredicateBuilder.True<View_UserAndRole>();
                if (!string.IsNullOrEmpty(Request.Params["RoleID"]))
                {
                    ExpWhere = ExpWhere.And(p => Convert.ToInt32(p.RoleID) == Convert.ToInt32(Request.Params["RoleID"].ToString()));
                }
                if (!string.IsNullOrEmpty(Request.Params["UName"]))
                {
                    ExpWhere = ExpWhere.And(p => p.UName.Contains(Request.Params["UName"].ToString()));
                }
                if (!string.IsNullOrEmpty(Request.Params["IsLock"]))
                {
                    ExpWhere = ExpWhere.And(p => Convert.ToInt32(p.IsLock) == Convert.ToInt32(Request.Params["IsLock"].ToString()));
                }
                if (!string.IsNullOrEmpty(Request.Params["LoginState"]))
                {
                    ExpWhere = ExpWhere.And(p => p.LoginState == Convert.ToInt32(Request.Params["LoginState"]));
                }
                var UserList = mql.LinQObj.View_UserAndRole.Where(ExpWhere);


猜你喜欢

转载自blog.csdn.net/michaelgong/article/details/7226016
今日推荐