Linq动态条件
很多情况下,我们开发程序,需要动态拼接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动态条件的更多相关文章
- [C#] Linq 动态条件查询
应用背景:以货品为例,在基础数据中配置货品的判断规则,要根据这个规则筛选出符合条件的集合. 创建货品类 public class Product { public string Name { get; ...
- Linq to Sql 动态条件另类实现方法
其实我也不知道是不是另类的,反正我找了好久园子里和其他资源. 无外乎两类 1,构造动态表达式的,这个真心繁琐,我是懒人,不想弄表达式. 2,拼SQL语句,直接执行,这个和ado.net就没有啥区别了. ...
- 白话LINQ系列2---以代码演进方式学习LINQ必备条件
今天,我们通过一个简单的示例代码的演进过程,来学习LINQ必备条件:隐式类型局部变量:对象集合初始化器:委托:匿名函数:lambda表达式:扩展方法:匿名类型.废话不多说,我们直接进入主题. 一.实现 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为s ...
- entity framework 动态条件
entity framework 动态条件 问题:在实际编码过程中,根据不同的选择情况,会需要按照不同的条件查询数据集 如:状态confirmStatus ,如果为空的时候,查询全部,如果有具体值的时 ...
- ibatis复用SQL片段、引入片段 动态条件增加
1:ibatis复用SQL片段.引入片段 使用[sql]和[include]标签: 通常情况下,你会这样写:xml 代码 <select id="selectItemCount&qu ...
- LinQ动态排序
LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使2 ...
- Linq动态查询与模糊查询 ---转
Linq动态查询与模糊查询(带源码示例) 继LINQ动态组合查询PredicateExtensions讲解 ----- 在用上面的方法时遇到了些问题 解决 LINQ to Entities 不支持 L ...
- spring mongodb分页,动态条件、字段查询
使用MongRepository public interface VideoRepository extends MongoRepository<Video, String> { Vid ...
随机推荐
- jQuery .css color 重写 :hover样式没了
$("#quickSqlDiv a").css({"color":"red"}); $("#course a").css ...
- redis hash数据类型
我们可以将Redis中的Hashes类型看成具有String Key和String Value的map容器.所以该类型非常适合于存储值对象的信息.如Username.Password和Age等.如果H ...
- win10 上运行 curl_init() 函数一直报错的解决办法
[问题现象] 1.把 APACHE 的 ZIP 包解压到目录,比如 d:\apache24\ 2.把 PHP 的 ZIP 包解压到目录,比如:d:\php56\ apache 与 php 与 MySQ ...
- 将一个数组分成奇数部分和偶数部分,并分别排好序 CVTE
给定一个数组,将奇数放到前面,偶数放到后面,各自排好序 (2016年3月12日晚上,CVTE笔试编程第一道题): 思路很简单: (1)先将数组中的奇数和偶数分开(利用两个指针遍历一遍即可,同时统计好数 ...
- 数据快照 (Database Snapshot)
数据库快照是指数据库某一指定时刻的情况,数据库快照提供了源数据库在创建快照时刻的只读,静态视图 . 数据库快照一旦创建就不会改变. 数据库快照在被数据库所有者显示删除前始终存在. 数据库快照用途: 快 ...
- iOS-详细解读Const
在过去开发中,几乎每一个人都会定义宏,因为这东西实在是好用,省去了代码量而且还不容易错,而我这篇文中所介绍的const可以完美替带宏定义. 并且苹果也建议大家抛弃宏定义而转投const ,并且swif ...
- jqm页面跳转问题
jqm里面页面跳转默认都是通过ajax请求的,必须重新刷新页面js方可有效,也就是js没有起作用,并不是js本身的问题,下面说说解决方法: 在使用jQuery Mobile进行Web开发中,当页面跳转 ...
- java覆盖和隐藏
隐藏指的是子类把父类的属性或者方法隐藏了,即将子类强制转换成父类后,调用的还是父类的属性和方法,而覆盖则指的是父类引用指向了子类对象,调用的时候会调用子类的具体方法. (1) 变量只能被隐藏(包括静态 ...
- nginx切割日志
#!/bin/bash ## Nginx 日志文件所在的目录 LOGS_PATH=/usr/local/nginx/logs ## 获取昨天的 yyyy-MM-dd YESTERDAY=$(date ...
- 装个蒜。学习下dispatch queue
dispatch queue的真髓:能串行,能并行,能同步,能异步以及共享同一个线程池. 接口: GCD是基于C语言的APT.虽然最新的系统版本中GCD对象已经转成了Objective-C对象,但AP ...