码迷,mamicode.com
首页 > 其他好文 > 详细

条件表达式工具类

时间:2016-01-19 17:20:26      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

internal class ParameterReplacer : ExpressionVisitor
{
public ParameterReplacer(ParameterExpression paramExpr)
{
this.ParameterExpression = paramExpr;
}

public ParameterExpression ParameterExpression { get; private set; }

public Expression Replace(Expression expr)
{
return this.Visit(expr);
}

protected override Expression VisitParameter(ParameterExpression p)
{
return this.ParameterExpression;
}
}

 

 

/// <summary>
/// 条件表达式工具类
/// </summary>
public static class ExpressionPredicate
{

const string DEFAULT="candidate";
/// <summary>
/// 创建表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> Create<T>() { return f => true; }

/// <summary>
/// True表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> True<T>() { return f => true; }

/// <summary>
/// False表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> False<T>() { return f => false; }

/// <summary>
/// Not操作
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expr"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expr)
{
var candidateExpr = expr.Parameters[0];
var body = Expression.Not(expr.Body);

return Expression.Lambda<Func<T, bool>>(body, candidateExpr);
}

/// <summary>
/// And操作
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="exp_left"></param>
/// <param name="exp_right"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> exp_left, Expression<Func<T, bool>> exp_right)
{
var candidateExpr = Expression.Parameter(typeof(T), DEFAULT);
var parameterReplacer = new ParameterReplacer(candidateExpr);

var left = parameterReplacer.Replace(exp_left.Body);
var right = parameterReplacer.Replace(exp_right.Body);
var body = Expression.And(left, right);

return Expression.Lambda<Func<T, bool>>(body, candidateExpr);
}

/// <summary>
/// Or操作
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="exp_left"></param>
/// <param name="exp_right"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> exp_left, Expression<Func<T, bool>> exp_right)
{
var candidateExpr = Expression.Parameter(typeof(T), DEFAULT);
var parameterReplacer = new ParameterReplacer(candidateExpr);

var left = parameterReplacer.Replace(exp_left.Body);
var right = parameterReplacer.Replace(exp_right.Body);
var body = Expression.Or(left, right);

return Expression.Lambda<Func<T, bool>>(body, candidateExpr);
}
}

条件表达式工具类

标签:

原文地址:http://www.cnblogs.com/zhshlimi/p/5142696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!