There are two ways to construct an expression tree in C#:
- let the compiler rewrite a lambda and store the result;
- construct it piecewise, calling factory methods provided by the
Expression
class.
The first approach is simple, but it doesn't let me integrate already existing subexpressions into a resulting expression, which is my main goal. (These subs are passed to me as function parameters by design).
In fact, the second approach itself is the subexpression composition process, but it is very cumbersome for anything but the simplest expressions with little to no nesting involved.
So, to get the best of two ways, while having to construct the trees piecewise, I look at copiler-generated expressions, and use them as hints. What I do is: write the code to construct a tree, while looking at the given tree. The whole process is quite a routine, so I wonder:
- are there tools to automate that? Couldn't find any myself.
- aside from codegens, are there some other possibilities to improve my method and make it more productive?
Here's the explaination of why I need this strange process at all.
Expression<Func<IEnumerable<N>, IEnumerable<N>, IEnumerable<N>>>
MyExpression = (src1, src2) =>
src1.SelectMany(outer => lookup[outer.Value1].Select(
inner => new N(outer, inner)));
Now, I am provided with two subexpressions, which are to be placed instead of outer.Value1
and new N(outer, inner)
. I can't use .Compile()
and utilise them as lambdas, because I have to provide the complete expression tree for further processing intact. I need a way to integrate them into MyExpression
, and the only method I'm aware of is to construct the whole tree via Expression
factories. But with more complex queries it gets extremely complex and error-prone.