using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions; namespace HYS.Fee.AppSrv
{
/// <summary>
/// 数据库上下文
/// </summary>
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
// build parameter 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 parameters from the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
} public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.And);
} public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.Or);
}
} public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map; public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
} public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
} protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}

用法:

Expression<Func<表名, bool>> expr = n => true;
expr = expr.And(n => n.PNAME.Contains(""));
expr = expr.Or(n => n.PID > );
context.表名.Where(expr).ToList()

最新文章

  1. 开源协议:LGPL协议、OSGi协议---打酱油的日子
  2. 作业三:WC项目
  3. [xsd学习]复合元素
  4. Black Box 分类: POJ 栈和队列 2015-08-05 14:07 2人阅读 评论(0) 收藏
  5. python小算法(一)
  6. homework_08
  7. php中位运算的应用:货品的状态
  8. SVN版本回滚~
  9. akoj-1267-独木舟上的荡漾
  10. FastDfs上传图片
  11. C/C++面试题:编写类String的构造函数、析构函数和赋值函数。
  12. Cocos Creator学习五:触摸和重力传感响应事件
  13. MyEclipse 编译错误 web项目中的 js,jsp报错 更改
  14. nginx 301重定向一种实现方法
  15. mybatis-plus快速入门使用
  16. grunt的用法一
  17. 003-SqlHelper.cs/Web.config
  18. 使用Maven清理项目
  19. jQuery事件处理(四)
  20. STL_容器共通能力

热门文章

  1. script放在body和放在head的区别
  2. 关于python 的 __future__
  3. nginx的学习
  4. resize2fs: 报错
  5. B. Game with string 思维问题转化
  6. 2019年9月2日,亲自最新JDK12.0.2和JRE1.8.0的下载和配置(64bit),被其他教程坑了几圈忍不住自己写一篇
  7. PMP概略学习上--基本思想和概念
  8. 题解 P5530 [BalticOI 2002]双调路径
  9. leetcode78.子集➕90.子集2
  10. Bugku-CTF之本地包含( 60)