Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a C# => Linq Expression compiler

I'm looking for the ability to convert entire methods into Expression trees. Writing it out would suck. :)

So (trivial example) given the following text:

public static int Add(int a, int b)
{
   return a + b;
}

I want to either get an in-memory object that represents this, or the following text:

ParameterExpression a = Expression.Parameter(typeof(int), "a");
ParameterExpression b = Expression.Parameter(typeof(int), "b");
var expectedExpression = Expression.Lambda<Func<int, int, int>>(
        Expression.Add(a,b),
        a,
        b
    );

Any ideas? Has anyone perhaps done something with Roslyn that can do this?

EDIT: Clarification: I want to suck in any C# method (for example, the one above) as text, and produce a resulting expression. Basically I'm looking to compile any given C# method into Expression trees.

like image 707
Shlomo Avatar asked Nov 15 '11 18:11

Shlomo


People also ask

Where can I get a cheap air conditioner?

The best platforms where you can get the air cheap ACs are , Flipkart, Tata Cliq, ShopClues and Amazon from a range of air conditioners like Voltas 103 DZS 0.8 Ton 3 Star Window AC, Voltas 102EZQ 0.75 Ton 2 Star Window AC, Voltas 102 EZQ 0.75 Ton 2 Star Window AC, Voltas WAC 103 LZF 1.5 Ton 3 Star Window AC and Lloyd ...


3 Answers

Yes Roslyn can do, but Roslyn has its own expression tree (they are called syntax trees), Roslyn tools allow you to load and execute expressions or statements.

You will have to write your own syntax tree walker to convert Roslyn syntax tree to your expression tree, but everything may not fit correctly.

like image 156
Akash Kava Avatar answered Oct 21 '22 10:10

Akash Kava


Why not:

Expression<Func<int,int,int>> expr = (a,b) => a + b;
like image 39
sinelaw Avatar answered Oct 21 '22 12:10

sinelaw


See billchi_ms answer at: http://social.msdn.microsoft.com/Forums/en-US/roslyn/thread/e6364fec-29c5-4f1d-95ce-796feb25a8a9

The short answer is that we may provide, or someone may write a Roslyn tree to ET v2, but Roslyn trees can represent the full languages of VB and C# while ETs v2 cannot (for example, type definitions or some ref-involved exprs).

like image 35
Bill Avatar answered Oct 21 '22 12:10

Bill