LINQ 多條件查詢 where 條件組建
阿新 • • 發佈:2018-12-08
1.新建一個靜態類
2.條件建立和呼叫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); } }
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);