Linq中怎么实现动态条件查询

发布时间:2021-07-20 11:17:36 作者:Leah
来源:亿速云 阅读:391

本篇文章给大家分享的是有关Linq中怎么实现动态条件查询,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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

Linq中怎么实现动态条件查询
实例讲解Linq动态条件查询

要实现这个功能,通常的做法是拼接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,< SPAN>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, < SPAN>bool>> end =       Expression.Lambda<FUNC<CUSTOMER, < SPAN>bool>>(condition, new ParameterExpression[] { c });

现在来解释Linq动态条件这段代码,首先构造了一个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)。

以上就是Linq中怎么实现动态条件查询,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 动态linq查询的实现方式是什么
  2. LINQ+Ajax动态查询怎么使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linq

上一篇:vue如何挂载路由到头部导航

下一篇:怎么修改gazebo物理参数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》