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

Expression拼接

程序员文章站 2022-09-26 21:57:04
public static class ExpressionHelp { /// /// Lambda表达式拼接 /// /// ///
public static  class expressionhelp
    {
        /// <summary>
        /// lambda表达式拼接
        /// </summary>
        /// <typeparam name="t"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="merge"></param>
        /// <returns></returns>
        public static expression<t> compose<t>(this expression<t> first, expression<t> second, func<expression, expression, expression> merge)
        {
            var map = first.parameters.select((f, i) => new { f, s = second.parameters[i] }).todictionary(p => p.s, p => p.f);
            var secondbody = parameterrebinder.replaceparameters(map, second.body);
            return expression.lambda<t>(merge(first.body, secondbody), first.parameters);
        }
        /// <summary>
        /// and扩展
        /// </summary>
        /// <typeparam name="t"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        public static expression<func<t1, t2, bool>> and<t1, t2>(this expression<func<t1, t2, bool>> first, expression<func<t1, t2, bool>> second)
        {
            return first.compose(second, expression.and);
        }
        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);
        }

        /// <summary>
        /// or扩展
        /// </summary>
        /// <typeparam name="t"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        public static expression<func<t1, t2, bool>> or<t1, t2>(this expression<func<t1, t2, bool>> first, expression<func<t1, t2, bool>> second)
        {
            return first.compose(second, expression.or);
        }
        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);
        }

    }