很多情况下,我们开发程序,需要动态拼接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. Eclipse导入Maven项目,使用server 启动报错,class 找不到,

    问题发现: 1.导入maven 项目后,用server 启动,选择项中没有这个项目 解决: 说明server 没有把该项目当成web项目,需要设置 项目右键 properties  ---- proj ...

  2. MMS搜索功能修改

    高通平台的MMS源码中提供了搜索功能,但要先选择分类(名字,号码,信息内容,彩信主题),再输入字符,根据分类进行搜索. 而在Contacts中却不需要分类,直接根据输入字符搜索任意匹配字段.相比之下, ...

  3. Reveal分析IOS界面,plist文件读取

    Reveal分析IOS界面,需要得到app的 softwareVersionBundleId上传到iphone中 , 而IOS8的iTunesMetadata.plist (设备路径/var/mobi ...

  4. Linux下chkconfig命令详解

    chkconfig命令主要用来更新(启动或停止)和查询系统服务的运行级信息.谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接. 使用语法:chkconfig [--ad ...

  5. CS0234: 命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Html、Ajax”(是否缺少程序集引用?)

    从SVN上down下来的程序,编译报了一大堆的错,发现是缺少引用,但是明明引用了,后来打开引用,发现system.web.mvc这个引用打着叹号,如图: 后来重新引用了本机的system.web.mv ...

  6. 字符串s中从第i个位置起取长度为len的子串,函数返回子串链表

    /*已知字符串采用带结点的链式存储结构(详见linksrting.h文件),请编写函数linkstring substring(linkstring s,int i,int len),在字符串s中从第 ...

  7. (转)LAMPer技能树

  8. Win7下安装一个装逼文本编辑器Atom + activate-power-mode插件

    Atom是Github推出的一个文本编辑器,搜索一下大概是给Web前端用的,最近比较火的是他的一个插件activate-power-mode,可以实现打字屏振效果. 用来装装逼还是挺适合的,本来想试试 ...

  9. css3简单的图片轮播

    <style> @-webkit-keyframes move{ %{left:0px;} %{left:-500px;} } #wrap{ width:500px; height:100 ...

  10. 【九度OJ】题目1202:排序

    题目描述: 对输入的n个数进行排序并输出. 输入: 输入的第一行包括一个整数n(1<=n<=100).    接下来的一行包括n个整数. 输出: 可能有多组测试数据,对于每组数据,将排序后 ...