【问题标题】:How to combine two expressions: result = exp1(exp2);如何组合两个表达式:result = exp1(exp2);
【发布时间】:2009-08-13 08:30:55
【问题描述】:

作为主题,在这种情况下如何将两个表达式组合成一个:

Expression<Func<IEnumerable<T>, IEnumerable<T>>> exp1;
Expression<Func<IEnumerable<T>, IEnumerable<T>>> exp2;

Expression<Func<IEnumerable<T>, IEnumerable<T>>> result = ???; // exp1(exp2)

【问题讨论】:

    标签: .net linq lambda expression


    【解决方案1】:

    这实际上只是组合两个Expression&lt;Func&lt;T, T&gt;&gt; 值的一种特定形式。这是一个这样做的例子:

    using System;
    using System.Linq.Expressions;
    
    public class Test
    {
        public static Expression<Func<T, T>> Apply<T>
            (Expression<Func<T, T>> first, Expression<Func<T, T>> second)
        {
            ParameterExpression input = Expression.Parameter(typeof(T), "input");
            Expression invokedSecond = Expression.Invoke(second,
                                                         new Expression[]{input});
            Expression invokedFirst = Expression.Invoke(first,
                                                        new[]{invokedSecond});
            return Expression.Lambda<Func<T, T>>(invokedFirst, new[]{input});
        }
    
        static void Main()
        {
            var addAndSquare = Apply<int>(x => x + 1,
                                          x => x * x);
    
            Console.WriteLine(addAndSquare.Compile()(5));
        }
    }
    

    如果你愿意,你可以很容易地用这些术语写ApplySequence

        public static Expression<Func<IEnumerable<T>, IEnumerable<T>>>
             ApplySequence<T>
                (Expression<Func<IEnumerable<T>, IEnumerable<T>>> first,
                 Expression<Func<IEnumerable<T>, IEnumerable<T>>> second)
        {
            return Apply(first, second);
        }
    

    【讨论】:

    • “new[]{invokedSecond}”是什么意思?它是否创建了一个调用Second 类型的数组?还是带有单个项目的对象数组调用了Second?
    • 这是一个隐式类型数组,根据元素的静态类型进行类型化——在这种情况下,它相当于new Express[] { invokedSecond }
    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多