如何组合两个表达式:result = exp1(exp2);

时间:2009-08-13 08:30:55

标签: .net linq lambda expression

作为主题,如何将两个表达式组合成一个表达式:

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

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

1 个答案:

答案 0 :(得分:8)

这实际上只是组合两个Expression<Func<T, T>>值的特定形式。这是一个这样做的例子:

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);
    }