linq 實現查詢字符串拼接 : And 和 OR 兩種方式


N年前我們是這樣來 拼接查詢字符串的:

// 何問起 hovertree.com
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();  
   } 

現在我們使用linq來實現上邊的代碼:

public void Test(string a, string b, string c,string d)  
       {  
           QueryContext query = new QueryContext();  
           var q = from 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();  //上邊的所有if,只有到此處才會執行  
       }// 何問起 hovertree.com

推薦:http://www.cnblogs.com/roucheng/p/dushubiji.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM