linq 实现查询字符串拼接 : And 和 OR 两种方式
2016-05-31 12:11
323 查看
N年前我们是这样来 拼接查询字符串的:
现在我们使用linq来实现上边的代码:
推荐:http://www.cnblogs.com/roucheng/p/dushubiji.html
// 何问起 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 实现动态 orderby
- 驱动开发利器Microsoft Windows Driver Kit 7.1.0下载
- Windows 7专业版安装VS2005与WinCE6.0开发环境
- jdk源码分析之ArrayList
- WebView输入框提示
- C++移位运算符
- inner join on, left join on, right join on的区别与介绍
- 关于list的ConcurrentModificationException 异常
- eclipse的黑科技之 代码段抽成新方法
- Reducing the Dimensionality of Data with Neural Networks
- Javascript权威指南
- java的各种类型转换汇总
- jQuery使用经验建议
- ZIMG -- 高性能图片服务器浅谈
- JS中使用apply方法通过不同数量的参数调用函数的方法
- Spring框架中的定时器 如何使用和配置
- 第二次冲刺阶段站立会议(八)
- GridPanel中getSelectionModel
- C#导出Excel按照指定格式设置单元格属性值
- POJ 3159 Candies【差分约束+SPFA】