N years ago we did this by stitching the query string:
public string Test (string A, string B, string c,string d) {String sql = ' 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 + "'";} Return SQL. ToString (); }
Now we use LINQ to implement the above code:
public void Test (string A, string B, string c,string d) {querycontext query = new Querycontext (); var q = to u in Query . Users Select U; 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 if above, only to be executed here}
PS: If the query string is not an and, but an OR
Such as:
public string Test (string A, string B, string c,string d) {String sql = ' 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 + "'";} Return SQL. ToString (); }
In this case, this can be done through LINQ:
public void Test (string a,string b,string c,string d) {querycontext query = new Querycontext (); var q1 = out U in query. Users where u.name== a && a!= "" | | U.age = b && b!= "" | | U.sex = = C && C!= "" | | U.address ==d && D!= "" Select U; Q1. ToList (); }