欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PredicateBuilder

程序员文章站 2022-08-08 23:30:16
using System; using System.Linq; using System.Linq.Expressions; namespace Oyang.Tool { public static class PredicateBuilder { public static Expression... ......
using system;
using system.linq;
using system.linq.expressions;

namespace oyang.tool
{
    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<func<t, bool>> and<t>(this expression<func<t, bool>> expr1, expression<func<t, bool>> expr2)
        {
            var invokedexpr = expression.invoke(expr2, expr1.parameters.cast<expression>());
            return expression.lambda<func<t, bool>>
                  (expression.andalso(expr1.body, invokedexpr), expr1.parameters);
        }

        public static expression<func<t, bool>> or<t>(this expression<func<t, bool>> expr1, expression<func<t, bool>> expr2)
        {
            var invokedexpr = expression.invoke(expr2, expr1.parameters.cast<expression>());
            return expression.lambda<func<t, bool>>
                  (expression.orelse(expr1.body, invokedexpr), expr1.parameters);
        }

        public static expression<func<t, bool>> and<t>(this expression<func<t, bool>> expr1, func<expression<func<t, bool>>> func)
        {
            expression<func<t, bool>> expr2 = func();
            var invokedexpr = expression.invoke(expr2, expr1.parameters.cast<expression>());
            return expression.lambda<func<t, bool>>
                  (expression.andalso(expr1.body, invokedexpr), expr1.parameters);
        }

        public static expression<func<t, bool>> or<t>(this expression<func<t, bool>> expr1, func<expression<func<t, bool>>> func)
        {
            expression<func<t, bool>> expr2 = func();
            var invokedexpr = expression.invoke(expr2, expr1.parameters.cast<expression>());
            return expression.lambda<func<t, bool>>
                  (expression.orelse(expr1.body, invokedexpr), expr1.parameters);
        }
    }
}