How to combine two expressions: result = exp1(exp2);
Asked Answered
B

1

6

As subject, how to combine two expressions into a single one for this case:

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

Expression<Func<IEnumerable<T>, IEnumerable<T>>> result = ???; // exp1(exp2)
Bimonthly answered 13/8, 2009 at 8:30 Comment(0)
A
8

This is really just a specific form of combining two Expression<Func<T, T>> values. Here's an example of doing that:

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

You could write ApplySequence in those terms easily, if you wanted to:

    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);
    }
Acrolith answered 13/8, 2009 at 8:34 Comment(2)
What does the "new[]{invokedSecond}" means? Does it creates an array of invokedSecond's type? Or an array of Objects with a single item invokedSecond?Bimonthly
It's an implicitly typed array, typed according to the static types of the elements - in this case it's equivalent to new Express[] { invokedSecond }.Acrolith

© 2022 - 2024 — McMap. All rights reserved.