Lambda to Expression tree conversion - c#

I will keep it really simple,
How do I get expression tree out of lambda??
or from query expression ?

You must assign the lambda to a different type:
// Gives you a delegate:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => x * 2;
The same goes for method arguments. However, once you've assigned such a lambda expression to a Func<> type, you can't get the expression tree back.

Konrad's reply is exact. You need to assign the lambda expression to Expression<Func<...>> in order for the compiler to generate the expression tree. If you get a lambda as a Func<...>, Action<...> or other delegate type, all you have is a bunch of IL instructions.
If you really need to be able to convert an IL-compiled lambda back into an expression tree, you'd have to decompile it (e.g. do what Lutz Roeder's Reflector tool does). I'd suggest having a look at the Cecil library, which provides advanced IL manipulation support and could save you quite some time.

Just to expand on Konrad's answer, and to correct Pierre, you can still generate an Expression from an IL-compiled lambda, though it's not terribly elegant. Augmenting Konrad's example:
// Gives you a lambda:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => f(x);

Related

What's the datatype of lambda-expressions?

i have a small question i just can't figure out myself, what is the datatype of a lambda-expression like this:
x => x>0
I hope you can help me.
It's just a Func<T, bool> where T is type of x.
In general, Func<T, TResult> is the one of predefined delegate types for a method that accepts one argument of type T (x in your case) and returns some value of the type TResult (bool in your case)
More info here
Lambda expressions don't have a definite type. The types that a lambda expression can be implicitly converted to is either delegate or Expression type.
You can find more information here
"Note that lambda expressions in themselves do not have a type because the common type system has no intrinsic concept of "lambda expression." However, it is sometimes convenient to speak informally of the "type" of a lambda expression. In these cases the type refers to the delegate type or Expression type to which the lambda expression is converted."
For your specific example some of the types to which the lambda can be assigned are:
Predicate<int> predicate = x => x > 0;
Func<int, bool> func = x => x > 0;
Expression<Func<int, bool>> expression = x => x > 0;

Lambda Expression definition (pedant )?

By just briefing a book (leading one) , one thing caught my eyes - the lambda expression definition :
A lambda expression is an unnamed method written in place of a
delegate instance.
in place of delegate instance ???
A delegate instance is an object that refers-to/encapsulate target method/s :
In the following sample The right side(where the lambda expression would be) is not a delegate instance. it is a method.
TransformerDelegate t = SquareMethod;
So the definition should have been corrected-to/mention :
lambda expression are unnamed method written in place of a method(!)
being referenced by delegate variable.
TransformerDelegate sqr = x => x * x;
^
|
---------------+
|
this is the location for method/anonymous methods.
do you see what I mean ? Am I right?
p.s. I did understand the msdn's one : ( but want to see if the book had made a mistake)
A lambda expression is an anonymous function that can contain
expressions and statements, and can be used to create delegates or
expression tree types.
The value of a lambda expression is a delegate instance.
So the book is probably referring to code like:
MySquareDelegate f1 = x => x * x;
MySquareDelegate f2 = new MySquareDelegate(MySquareMethod);
MySquareDelegate f3 = MySquareMethod; // just shorthand for the previous line
It is tricky stuff to explain in 1 sentence, your own version
lambda expression are unnamed method written in place of a method(!) being referenced by delegate variable.
is talking about "a method instead of a method", the original about "a method instead of a delegate instance" where the method is implicitly converted to a delegate instance. Both seem incomplete at least.
A definition of a lambda should also include that it is an inline method.
Other answers miss the fact that lambda expressions do not necessarily represent methods. Sometimes, they represent expression trees.
The compiler implicitly converts lambda expressions to one type of object or the other, depending on context.
To specify a method, you need to specify parameters and a body. In a lambda expression, these are separated by =>. Examples:
() => 4; //empty parameter list
x => x.ToString(); //one parameter
(a, b) => a.Equals(b); //two parameters
// ^^^^^^ ^^^^^^^^^^^^
// | |
// parameter list body
These lambda expressions can be converted to Func<int>, Func<object, string>, and Func<object, object, bool> respectively. The could also be converted to Expression<Func<int>>, Expression<Func<object, string>>, and Expression<Func<object, object, bool>> respectively.
An anonymous method:
delegate (object p, object q) { return string.Concat(p, q); }
// ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// parameter list body
Here are two examples of lambda conversion:
Func<object, object, bool> aDelegate = (o1, o2) => object.Equals(o1, o2);
Expression<Func<object, object, bool>> anExpressionTree = (o1, o2) => object.Equals(o1, o2);
In method group conversion, the parameters and method body are specified by overload resolution. To simplify a bit, the compiler looks at the methods with the indicated name and chooses the correct overload based on the context. For example, consider these overloads of SquareMethod:
int SquareMethod(int a) { return a * a; }
double SquareMethod(double a) { return a * a; }
These statements involve method group conversion and overload resolution:
Func<int, int> squareAnInt = SquareMethod;
Func<double, double> squareADouble = SquareMethod;
Finally, statement lambdas cannot be translated to expression trees:
Action<object> anAction = o => { Console.WriteLine(o); };
Func<object, int> aFunc = o =>
{
var s = (o ?? "").ToString();
Console.WriteLine(s);
return s.Length;
};
The C# language specification (somewhat confusingly) uses the term "anonymous function" to cover both lambda expressions and anonymous methods. Anonymous functions can be implicitly converted to a compatible delegate type, and so can method groups. Therefore, if we have a delegate type called DelegateType, and a declaration/assignment like this:
DelegateType d = [something];
Then [something] can be a method group or an anonymous function. In other words, it can be a method group, an anonymous method or a lambda expression.
So, your correction to the book's text would be better to say "in place of a method group", but I would say
A lambda expression is an unnamed method that, like a named method group, can be used to create a delegate instance.
I might also add
In some cases, a lambda expression can be used to create an expression tree rather than a delegate instance.
Basically a delegate is nothing but an object that knows how to call a specific method. So a delegate instance literally acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method.

what is the use of ()=> in silverllight

Can you say what is the use of the ()=> and =>? I saw this in a code. I did not get any reference for this.
this.Dispatcher.BeginInvoke(()=>
{
//some thing..
};
=> is the lambda operator in C# and is read as "goes to". A lambda expression is an anonymous function and can be used to create a delegate.
Your example takes no arguments as indicated by the empty parens preceding the lambda operator. A lambda expression with one argument might look like this:
n => n.toString()
That expression would return the string representation of n, when invoked. A lambda expression can have multiple arguments as well, contained in parentheses:
(n, f) => n.toString(f)
A common use would be in a Func<T>:
Func<int, string> getString = n => n.toString();
int num = 7;
string numString = getString(num);
This is, of course, a silly example, but hopefully helps to illustrate its use.
This notation is that of a lambda expression which takes no argument. If the lambda expression made use of arguments they would be declared in the empty set of parenthesis as in say...
this.Dispatcher.BeginInvoke((x, y) => { do some' with x and/or y }, 12, somevar);
In a nutshell, lambda expressions allows creating "nameless" functions, right where they are needed.
In the example of the question, the BeginInvoke() method requires its first parameter to be a delegate (a "pointer to a method"), which is exactly what this lambda expression provides.
It's a lambda expression that has no parameters.
Check out this page http://codebetter.com/karlseguin/2008/11/27/back-to-basics-delegates-anonymous-methods-and-lambda-expressions/
If you don’t have any parameters, like in our example, you use empty
paranthesis:
() => {…}

Evaluate C# expression inside another expression

I want to use an expression in another one:
Expression<Func<double, double>> f = x => x * x * 27 + blah ... expression with x;
Expression<Func<double, double>> g = y => 3 + 8 * f.Compile()(y) * y * blah... expression with y and f(y);
This will not work when sent to LINQ to SQL because f.Compile() is unknown to SQL.
How do you evaluate the expression f on the variable y without compiling it, but still using normal syntax to define g?
I don't want to have to define all of g with some unreadable Expression.Add/Expression.Multiply etc. statements.
Thanks.
Take a look at Calling functions in LINQ queries and LINQ Extensions project. CLinq part is irrelevant to your question, but it also includes LinqExt library, which is just what are you looking for. The same approach is also used by LinqKit which also provides other useful extensions for Linq.

What does '=>' do in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Lamda Explanation and what it is as well as a good example
What is the => token called?
I have seen this code:
myContext.SomeEntities.Single(x => x.code == code);
And I don´t know what does the => operator do.
Every search on google about the operator returns no results.
Thank you.
The => operator designates a Lambda Expression:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
static void Main(string[] args)
{
Func<int, int> func = x => x * x;
int j = func(5);
// j == 25
}
Lambda expressions, very cool.
http://msdn.microsoft.com/en-us/library/bb397687.aspx
This is defining a lambda. You can read it "x goes to x.code equals code," and it means that given x, return the result of the given comparison.
It signals that the code is a lambda expression.
More info:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
They are related to lambda expressions.
You can read about Lambda Expressions here:
http://www.rvenables.com/2009/03/practical-introduction-to-lambda-expressions/

Categories

Resources