SoFunction
Updated on 2025-03-06

Use of C# conditional splicing Expression<Func<T, bool>>>

Use code

Special note: When splicing conditions, the used condition strID and strBir must be independent.

var predicate = <Student>();
predicate = (it => ().Contains(strID));
predicate = (it => ().Contains(strBir));
predicate = (it => ().Contains(strSex));
predicate = (it =>  == 20);
var lst = <Student>.Where(predicate).ToList();

Tools

using System;
using ;

namespace 
{
    public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> GetTrue<T>() { return f => true; }
        public static Expression<Func<T, bool>> GetFalse<T>() { return f => false; }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return <T>(second, );
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return <T>(second, );
        }

        private static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2, Func<Expression, Expression, BinaryExpression> func)
        {
            var parameter = (typeof(T));

            var leftVisitor = new ReplaceExpressionVisitor([0], parameter);
            var left = ();

            var rightVisitor = new ReplaceExpressionVisitor([0], parameter);
            var right = ();

            return <Func<T, bool>>(
                func(left, right), parameter);
        }

        private class ReplaceExpressionVisitor : ExpressionVisitor
        {
            private readonly Expression _oldValue;
            private readonly Expression _newValue;

            public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
            {
                _oldValue = oldValue;
                _newValue = newValue;
            }

            public override Expression Visit(Expression node)
            {
                if (node == _oldValue)
                    return _newValue;
                return (node);
            }
        }
    }
}

This is the article about the use of C# conditional splicing Expression<Func<T, bool>>. For more related contents of C# conditional splicing Expression<Func<T, bool>>, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!