LINQ implements query string concatenation: And and or two ways

Source: Internet
Author: User

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

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.