N years ago we did this to splice the query string:
Public stringTest (stringAstringBstringCstringd) {stringsql ="SELECT * from Users WHERE 1=1"; if(!string. IsNullOrEmpty (a)) {SQL+="and name= '"+ A +"'"; } if(!string. IsNullOrEmpty (b)) {SQL+="and age= '"+ B +"'"; } if(!string. IsNullOrEmpty (c)) {SQL+="and sex= '"+ C +"'"; } if(!string. IsNullOrEmpty (d)) {SQL+="and address= '"+ D +"'"; } returnSQL. ToString (); }
Now we use LINQ to implement the above code:
Public voidTest (stringAstringBstringCstringd) {querycontext query=NewQuerycontext (); varQ = fromUinchquery. UsersSelectu; if(!string. IsNullOrEmpty (a)) {Q= Q.where (p = = P.name = =a); } if(!string. IsNullOrEmpty (b)) {Q= Q.where (p = = P.age = =b); } if(!string. IsNullOrEmpty (c)) {Q= Q.where (p = = P.sex = =c); } if(!string. IsNullOrEmpty (d)) {Q= Q.where (p = = P.address = =d); } q.tolist (); //all of the above if, only to be executed here}
PS: If the query string is not and, but is or
Such as:
Public stringTest (stringAstringBstringCstringd) {stringsql ="SELECT * from Users WHERE 1=1"; if(!string. IsNullOrEmpty (a)) {SQL+="OR name= '"+ A +"'"; } if(!string. IsNullOrEmpty (b)) {SQL+="OR age= '"+ B +"'"; } if(!string. IsNullOrEmpty (c)) {SQL+="OR sex= '"+ C +"'"; } if(!string. IsNullOrEmpty (d)) {SQL+="OR address= '"+ D +"'"; } returnSQL. ToString (); }
In this case, this can be achieved through LINQ:
Public voidTest (stringAstringBstringCstringd) {querycontext query=NewQuerycontext (); varQ1 = fromUinchquery. Userswhereu.name== a && a! =""|| U.age = = B && b! =""|| U.sex = = c && c! =""|| U.address ==d && D! ="" Selectu; Q1. ToList (); }
LINQ implements query string concatenation: And and or two ways