LINQ implementation Query string concatenation: And and or two ways

Source: Internet
Author: User


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 (); }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.