zoukankan      html  css  js  c++  java
  • linq 实现查询字符串拼接 : And 和 OR 两种方式

    1. N年前我们是这样来 拼接查询字符串的:

      [c-sharp] view plain copy
       
      1. public string Test(string a, string b, string c,string d)  
      2.    {  
      3.        string sql = "SELECT * FROM Users WHERE 1=1";  
      4.        if (!string.IsNullOrEmpty(a))  
      5.        {  
      6.            sql += " AND name='" + a + "'";  
      7.        }  
      8.        if (!string.IsNullOrEmpty(b))  
      9.        {  
      10.            sql += " AND age='" + b+ "'";  
      11.        }  
      12.        if (!string.IsNullOrEmpty(c))  
      13.        {  
      14.            sql += " AND sex='" + c + "'";  
      15.        }  
      16.        if (!string.IsNullOrEmpty(d))  
      17.        {  
      18.            sql += " AND address='" + d + "'";  
      19.        }  
      20.        return sql.ToString();  
      21.    }  
       

      现在我们使用linq来实现上边的代码:

      [c-sharp] view plain copy
       
      1. public void Test(string a, string b, string c,string d)  
      2.        {  
      3.            QueryContext query = new QueryContext();  
      4.            var q = from u in query.Users  
      5.                     select u;  
      6.            if (!string.IsNullOrEmpty(a))  
      7.            {  
      8.                q = q.Where(p => p.name == a);  
      9.            }  
      10.            if (!string.IsNullOrEmpty(b))  
      11.            {  
      12.                q = q.Where(p => p.age == b);  
      13.            }  
      14.            if (!string.IsNullOrEmpty(c))  
      15.            {  
      16.                q = q.Where(p => p.sex == c);  
      17.            }  
      18.            if (!string.IsNullOrEmpty(d))  
      19.            {  
      20.                q = q.Where(p => p.address == d);  
      21.            }  
      22.            q.ToList();  //上边的所有if,只有到此处才会执行  
      23.        }  
  • 相关阅读:
    ASP.NET中的DataBinder.Eval用法
    jquery Ajax调用asmx和ashx代码示例三级联动
    项目中使用的架构
    asp.net(c#)上传图片到数据库
    asp.net(c#)从数据库里读取图片并显示到页面
    一款好的UI草图设计软件
    Windows Azure云平台(无须提供信用卡)[转]
    推荐8个超棒的学习 jQuery 的网站
    推荐两个界面原型设计工具GUIDesignStudio 和 Mockups For Desktop
    在VS2010上使用C#调用非托管C++生成的DLL文件(图文讲解)
  • 原文地址:https://www.cnblogs.com/tsql/p/8570893.html
Copyright © 2011-2022 走看看