在开发项目的过程中,我们经常会遇到这样的需求,动态组合条件的查询。比如淘宝中的高级搜索:

要实现这个功能,通常的做法是拼接SQL查询字符串,不管是放在程序中或是在存储过程中。现在出现了Linq,下面来看看用Linq是怎样实现动态条件查询?

还是以Northwind数据库为例,如果要查询所有CustomerID以A或者B字母开头的Customer,一般我们会这样写:

 var results = ctx.Customers.Where(c => c.CustomerID.StartsWith("A") || c.CustomerID.StartsWith("B"));

如果需求改变,还要查询出以X字母或者Y字母开头的Customer,那可以增加查询条件:

 var results = ctx.Customers.Where(c => c.CustomerID.StartsWith("A") || c.CustomerID.StartsWith("B")|| c.CustomerID.StartsWith("X") || c.CustomerID.StartsWith("Y"));

不过如果该需求不确定呢?我们不知道具体是哪些字母,可能传过来的是一个字符串数组:

 string[] starts = ....var results = ctx.Customers.Where(c => ?);

我们可能很自然的这样写,虽然很清楚要做什么,但是很可惜编译不通过,编译器并不允许我们像这样来组合条件。

 Expression<Func<Customer,bool>> condition = cus => true;foreach (string s in starts){condition = cus => cus.CustomerID.StartsWith(s) || condition(cus);}

在Linq中提供一些方法允许我们动态构造Lambda表达式。如Expression.Call, Expression.Or, Expression.And,这样代码就可以写成:

 ParameterExpression c = Expression.Parameter(typeof(Customer), "c");
 Expression condition = Expression.Constant(false);foreach (string s in starts){Expression con = Expression.Call(Expression.Property(c, typeof(Customer).GetProperty("CustomerID")),typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),Expression.Constant(s));condition = Expression.Or(con, condition);}Expression<Func<Customer, bool>> end =Expression.Lambda<Func<Customer, bool>>(condition, new ParameterExpression[] { c });

现在来解释这段代码,首先构造了一个ParameterExpression对象,它作为参数传到Lambda表达中(相当于c => c.CustomerID.StartsWith("A")这里的c)。然后用值为false的Expression用来初始化该表达式(Expression.Constant(false))。

  Expression con = Expression.Call(Expression.Property(c, typeof(Customer).GetProperty("CustomerID")),typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),Expression.Constant(s));
  condition = Expression.Or(con, condition); 

上面这段代码是重头戏,用Expression.Call方法动态构造一个表达式,其中Expression.Property(c, typeof(Customer).GetProperty("CustomerID"))转换为c.CustomerID,typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) })表示string的StartsWith(string)方法,Expression.Constant(s)表示字符串常量,这个方法可以表示成:c.CustomerID.StartsWith(s)。然后调用Expression.Or方法组合各个条件(根据逻辑关系不同调用不同的方法,如or,and...)。

最后构造成Lambda表达式,现在就可以使用它了 ctx.Customers.Where(end)。

但是这个并不是最好的解决方法,使用这种方式生成的Lambda表达式,由于用到了反射,这样编译器不能检查错误,很可能因为一个字母写错导致运行时抛出异常。因此,要用一个更好的方案,既能满足我们的要求,又能让编译器更好的支持,就留到下一篇文章说吧。

转载于:https://www.cnblogs.com/blusehuang/archive/2007/07/13/816970.html

Linq之动态条件(1)相关推荐

  1. Linq to Sql 动态条件另类实现方法

    其实我也不知道是不是另类的,反正我找了好久园子里和其他资源. 无外乎两类 1,构造动态表达式的,这个真心繁琐,我是懒人,不想弄表达式. 2,拼SQL语句,直接执行,这个和ado.net就没有啥区别了. ...

  2. 列表页的动态条件搜索

    之前在搞.net的时候,我们可以借助强大的ExpressionTree来解决,之前有一篇是微软的EntityFramework表达式转换:Linq to Entity经验:表达式转换,是将一种表达式转 ...

  3. mybatis-plus在Mapper类中使用@select标签进行多表联合动态条件查询

    1.单表动态条件查询 1)单字段作为参数 直接用@param设置的值作为注入就好了 @Select("select * from ppms_person_message where crea ...

  4. springDataJpa入门教程(5)-单表动态条件查询+分页

    springDataJpa入门教程 springDataJpa入门教程(1)-基于springBoot的基本增删改查 springDataJpa入门教程(2)-Specification动态条件查询+ ...

  5. mongorepository查询条件_MongoDB动态条件之分页查询

    一.使用QueryByExampleExecutor 1. 继承MongoRepositorypublic interface StudentRepository extends MongoRepos ...

  6. java+criteriaquery_Hibernate动态条件查询(Criteria Query)

    1.创建一个Criteria实例 net.sf.hibernate.Criteria这个接口代表对一个特定的持久化类的查询.Session是用来制造Criteria实例的工厂. Criteria cr ...

  7. C# 动态 条件 组合_3D模型+平滑,在PPT中实现动态呈现

    营长说 微软的Office365软件中有个3D模型功能,很多人没有用过或者没有找到合适的3D模型文件.今天营长给你介绍如何应用Office365中的在线3D模型资源,并用动画和切换功能动态展示呈现.这 ...

  8. ibatis动态条件匹配标签dynamic prepend=WHERE

    1.项目中xml文件 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE sqlMap ...

  9. 实现Excel行插入行删除特殊处理,单元格合并及动态条件单元格公式自动计算功能的VBA 宏示例

    最近的项目中,用到了很多Excel的VBA宏功能,用户的新需求也有很多需要用VBA宏来实现.为满足业务需求, 自己搜索网上的相关资料,尝试不同的解决方法,最终解决了用户的需求,在此记录下来,做一个总结 ...

最新文章

  1. matlab最小分类错误全局二值化算法
  2. 高红冰:“五新”创新乡村商业实践
  3. UA PHYS515A 电磁理论V 电磁波与辐射11 简单辐射问题 电偶极子的辐射
  4. mysql隔离级别 简书_数据库事务和四种隔离级别
  5. 信息系统项目管理师:第二三章:信息系统项目管理基础与立项管理
  6. 使用yum来下载RPM包而不进行安装
  7. 搜索引擎学习(二)Lucene创建索引
  8. 单曲《我是一个程序员》
  9. php调用restful接口_如何使用PHP编写RESTful接口
  10. LeetCode 260. Single Number III
  11. crossdomain.xml跨越
  12. 拓端tecdat|R语言优化交易系统:用平行坐标图可视化系统参数优化结果
  13. ZebraDesigner3 打印到.prn文件乱码
  14. 用简单易懂的例子解释隐马尔可夫模型
  15. APP手机设备模拟器在线测试工具Responsinator
  16. 服务器运行几年后搬迁,服务器搬迁之后的准备工作和应对
  17. 云业务“探路” 中国联通成立产业互联网子公司
  18. word文件太大怎么压缩到最小-word压缩教程
  19. python中numpy.sum()函数
  20. Mac新手入门以及常用软件推荐

热门文章

  1. freemarker空格问题
  2. 【CCCC】L2-029 特立独行的幸福 (25分),模拟题,set用法
  3. linux限制堆栈大小,进程超过RedHat Enterprise Linux 6的线程堆栈大小限制?
  4. 运维学python哪部分_初入运维的小伙伴,别再问需不需要学Python了
  5. mac 查看环境变量_Mac开工利器Homebrew介绍
  6. jquery隐式迭代
  7. wifi协议_图解 802.11wifi协议
  8. 异步类随机多址接入分析
  9. 网络地址转换协议NAT详解
  10. OpenGL基础30:模板测试