We need a method to get the code that would build this expression tree

There are two ways to build an expression tree in C #:

  • let the compiler rewrite the lambda and store the result;
  • build it piece by piece by calling the factory methods provided by the class Expression

    .

The first approach is simple, but it doesn't allow me to integrate the already existing subexpressions into the resulting expression, which is my main goal. (These subsets are passed to me as function parameters by design).

In fact, the second approach is itself a process of subexpression composition, but it is very cumbersome for anything but the simplest expressions, in which little is involved.

So, to get the best out of the two, even though you need to build tree pieces, I look at the expressions generated by the multiplier and use them as clues. I do this: write the code to build a tree by looking at the given tree. The whole process is pretty mundane, so I wonder:

  • Are there tools to automate this? Couldn't find anyone.
  • Besides the codegens, are there other ways to improve my method and make it more productive?

It explains 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 have two subexpressions to be placed in place of outer.Value1

and new N(outer, inner)

. I cannot use .Compile()

and use them as lambdas because I have to provide a complete expression tree for further processing. I need a way to integrate them in MyExpression

, and the only method I know of is building the whole tree through factories Expression

. But with more complex queries, it becomes extremely complex and error prone.

+3


source to share


1 answer


Besides the codegens, are there other ways to improve my method and make it more productive?

Basically, you want to write a class that extends ExpressionVisitor that replaces some component of one expression with chunks from another expression.

Are there tools to automate this?

LINQKit does exactly that. Using website examples:



Expression<Func<Purchase,bool>> criteria1 = p => p.Price > 1000;
Expression<Func<Purchase,bool>> criteria2 = p => criteria1.Invoke (p)
                                             || p.Description.Contains ("a");

Console.WriteLine (criteria2.Expand().ToString());

      

Output:

p => ((p.Price> 1000) || p.Description.Contains ("a"))

+2


source







All Articles