很多情况下,我们开发程序,需要动态拼接SQL查询语句;

比如  select top 1 * from User where age= 18  and  name = 'renruiquan'

其中红色的代码,是我们需要根据查询条件是否为空,来判,要不要加在查询的SQL里;

换成Linq里就不能这么直接的去拼接了,好在国外的大神有给我们解决方案。下面直接上代码:

(新手同学不需要关心代码具体是怎么实现的,只需要知道怎么调用就好。当然,你能研究一下,给自己充电,也是再好不过了)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace JQ.GameClient.Common
{
/// <summary>
/// Enables the efficient, dynamic composition of query predicates.
/// </summary>
public static class PredicateBuilder
{
/// <summary>
/// Creates a predicate that evaluates to true.
/// </summary>
public static Expression<Func<T, bool>> True<T>() { return param => true; } /// <summary>
/// Creates a predicate that evaluates to false.
/// </summary>
public static Expression<Func<T, bool>> False<T>() { return param => false; } /// <summary>
/// Creates a predicate expression from the specified lambda expression.
/// </summary>
public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; } /// <summary>
/// Combines the first predicate with the second using the logical "and".
/// </summary>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
} /// <summary>
/// Combines the first predicate with the second using the logical "or".
/// </summary>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
} /// <summary>
/// Negates the predicate.
/// </summary>
public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
{
var negated = Expression.Not(expression.Body);
return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);
} /// <summary>
/// Combines the first expression with the second using the specified merge function.
/// </summary>
static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
// zip parameters (map from parameters of second to parameters of first)
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f); // replace parameters in the second lambda expression with the parameters in the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // create a merged lambda expression with parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
} /// <summary>
/// ParameterRebinder
/// </summary>
class ParameterRebinder : ExpressionVisitor
{
/// <summary>
/// The ParameterExpression map
/// </summary>
readonly Dictionary<ParameterExpression, ParameterExpression> map; /// <summary>
/// Initializes a new instance of the <see cref="ParameterRebinder"/> class.
/// </summary>
/// <param name="map">The map.</param>
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
} /// <summary>
/// Replaces the parameters.
/// </summary>
/// <param name="map">The map.</param>
/// <param name="exp">The exp.</param>
/// <returns>Expression</returns>
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
} /// <summary>
/// Visits the parameter.
/// </summary>
/// <param name="p">The p.</param>
/// <returns>Expression</returns>
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement; if (map.TryGetValue(p, out replacement))
{
p = replacement;
} return base.VisitParameter(p);
}
}
} }

代码调用:

            //动态构造查询条件
var predicate = PredicateBuilder.True<UserInfo>();
       //查询用户状态为1的数据
predicate = predicate.And(x => x.status == 1); if (!string.IsNullOrEmpty(name))
{
         //如果查询的用户名不为空,则拼接表达式
predicate = predicate.And(x => x.name == name);
} var list = bll.GetList<UserInfo>(predicate,o=>o.orderno);

其中UserInfo为用户表的实体类。

list即为查询的结果。

Linq动态条件的更多相关文章

  1. [C#] Linq 动态条件查询

    应用背景:以货品为例,在基础数据中配置货品的判断规则,要根据这个规则筛选出符合条件的集合. 创建货品类 public class Product { public string Name { get; ...

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

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

  3. 白话LINQ系列2---以代码演进方式学习LINQ必备条件

    今天,我们通过一个简单的示例代码的演进过程,来学习LINQ必备条件:隐式类型局部变量:对象集合初始化器:委托:匿名函数:lambda表达式:扩展方法:匿名类型.废话不多说,我们直接进入主题. 一.实现 ...

  4. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为s ...

  5. entity framework 动态条件

    entity framework 动态条件 问题:在实际编码过程中,根据不同的选择情况,会需要按照不同的条件查询数据集 如:状态confirmStatus ,如果为空的时候,查询全部,如果有具体值的时 ...

  6. ibatis复用SQL片段、引入片段 动态条件增加

    1:ibatis复用SQL片段.引入片段  使用[sql]和[include]标签: 通常情况下,你会这样写:xml 代码 <select id="selectItemCount&qu ...

  7. LinQ动态排序

    LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使2 ...

  8. Linq动态查询与模糊查询 ---转

    Linq动态查询与模糊查询(带源码示例) 继LINQ动态组合查询PredicateExtensions讲解 ----- 在用上面的方法时遇到了些问题 解决 LINQ to Entities 不支持 L ...

  9. spring mongodb分页,动态条件、字段查询

    使用MongRepository public interface VideoRepository extends MongoRepository<Video, String> { Vid ...

随机推荐

  1. 微信公众账号开发之N个坑(二)

    上篇说到微信公众账号的几个坑,前面五个,已经说到菜单,宝宝继续往下赘述了.可惜,还不知道宝宝的宝宝到底是不是心疼宝宝呢,完了,我凌乱了... 回到正题,我们就不吐槽其他的了,上一篇说到微信的菜单了,那 ...

  2. .net 微信分享功能

    微信在国内目前无疑是最火的社交软件,智能手机装机必备. 微信api有java,php,Python语言的demo, 为毛没有C#的范例?兄长今天给各位带来一个.不叫哥(割)了,A股今天又暴跌[3912 ...

  3. IE事件模型,如何给IE和非IE浏览器添加事件

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title> ...

  4. sublime text3使用小结

    一.下载 http://www.sublimetext.com/2   sublime text2下载页 http://www.sublimetext.com/3   sublime text3下载页 ...

  5. 中国UTM分区

    高斯-克吕格投影是“等角横切圆柱投影”,投影后中央经线保持长度不变,即比例系数为1: UTM投影是“等角横轴割圆柱投影”,圆柱割地球于南纬80度.北纬84度两条等高圈,投影后两条割线上没有变形,中央经 ...

  6. 小清新cygwin,正在诞生中

    正文保留. 评论记录点滴.最后汇总.

  7. 老毛桃u盘装系统制作工具

    老毛桃[url=http://www.laomaotao.cn.com/]一键u盘装系统下载[/url]告别繁琐,简单易用,一盘两用,携带方便.不需要任何技术基础,一键制作,自动完成制作,平时当U盘使 ...

  8. nodejs中Stream的理解

    在nodejs中可以通过fs模块读写文件,我们来看下fs模块提供的接口: fs.readFile(filename, callback) 异步读取文件. filename是读取文件的文件名,如果是相对 ...

  9. Linux内核分析之可执行程序的装载和启动

    一.内容分析 1.可执行文件的创建 (1)预处理阶段 预处理过程读入源代码,检查包含预处理指令的语句和宏定义,并对源代码进行相应的转换,预处理过程还会删除程序中的注释和多余的空白字符.其中预处理指令主 ...

  10. (转)C# foreach 中获取索引index的方法

    在C# 开发中往往使用foreach 循环语句 来代替for循环语句.foreach 比 for 更加简洁高效.           foreach :                 foreach ...