码迷,mamicode.com
首页 > 其他好文 > 详细

linq 实现查询字符串拼接 : And 和 OR 两种方式

时间:2016-05-31 13:54:44      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

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

linq 实现查询字符串拼接 : And 和 OR 两种方式

标签:

原文地址:http://www.cnblogs.com/roucheng/p/linqpingjie.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!