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:
() => {…}
Related
I found a little script that I understand fully. I've got a string with "1 -2 5 40" for example. It reads the input string, splits it into a temporary array. Then this array is parsed and each element is transformed into an integer. The whole thing is order to give the nearest integer to zero.
But what I don't understand is the notation Select(int.Parse). There is no lambda expression here and the method int.Parse isn't called with brackets. Same with the OrderBy(Math.Abs)
Thank you in advance =)
var temps = Console.ReadLine().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
var result = temps.Select(int.Parse)
.OrderBy(Math.Abs)
.ThenByDescending(x => x)
.FirstOrDefault();
int.Parse is a method group - what you're seeing is a method group conversion to a delegate. To see it without LINQ:
Func<string, int> parser = int.Parse;
int x = parser("10"); // x=10
It's mostly equivalent to:
Func<string, int> parser = text => int.Parse(text);
... although there are plenty of differences if you want to go into the details :)
Select(int.Parse) is nearly equivalent to Select(x => int.Parse(x)).
The Select demands an Func<T, R>, which in this case is also the signature of int.Parse (it has a single parameter with a return value). It convers the method group to the matching delegate.
In this case Func<T, R> will map to Func<string, int>, so it matches the int Parse(string) signature.
int.Parse is a method with signature string -> int (or actually, a method group, with different signatures. But the compiler can infer you need this one, because it is the only one that fits.
You could use this method as a parameter wherever you would supply a delegate parameter with the same signature.
The parameter for .Select() is Func<T1, T2>() where T1 is the input parameter (the individual values of temps), and T2 is the return type.
Typically, this is written as a lambda function: x => return x + 1, etc. However, any method that fits the generic definitions can be used without having to be written as a lambda since the method name is the same as assigning the lambda to a variable.
So Func<string, int> parseInt = s => Convert.ToInt32(s); is syntactically equivalent to calling the method int.Parse(s).
The language creates the shortcut of automatically passing the Func parameter to the inside method to create more readable code.
Select LINQ IEnumerable<> extension method signature looks like that:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
Look at the selector argument. In your case you pass to Select .Net standard function int.Parse which has signature:
public static int Parse(
string s
)
.Net compiler can convert delegates to Func<...> or Action<...>. In case of int.Parse it can be converted to Func and therefore can be passed as argument to Select method.
Exactly the same with OrderBy. Look at its signature too.
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.
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/
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);
Forgive me if this screams newbie but what does => mean in C#? I was at a presentation last week and this operator (I think) was used in the context of ORM. I wasn't really paying attention to the specifics of syntax until I went back to my notes.
In C# the lambda operator is written "=>" (usually pronounced "goes to" when read aloud). It means that the arguments on the left are passed into the code block (lambda function / anonymous delegate) on the right.
So if you have a Func or Action (or any of their cousins with more type parameters) then you can assign a lambda expression to them rather than needing to instantiate a delegate or have a separate method for the deferred processing:
//creates a Func that can be called later
Func<int,bool> f = i => i <= 10;
//calls the function with 12 substituted as the parameter
bool ret = f(12);
Since nobody mentioned it yet, in VB.NET you'd use the function keyword instead of =>, like so:
dim func = function() true
'or
dim func1 = function(x, y) x + y
dim result = func() ' result is True
dim result1 = func1(5, 2) ' result is 7
It's shorthand for declaring a lambda.
i => i++
is (sort of) the same as writing:
delegate(int i)
{
i++;
}
In the context of:
void DoSomething(Action<int> doSomething)
{
doSomething(1);
}
DoSomething(delegate(int i) { i++; });
//declares an anonymous method
//and passes it to DoSomething
which is (sort of) the same as writing:
void increment(int i)
{
i++;
}
Just without giving it a name, it allows you to declare a function in-line, known as an "anonymous" function.
When said aloud the operator is the lambda (goes to) operator which helps to define the anonymous delegate that you're defining in the lambda.
A common place to see this is with an event handler. You will often have a a page load type event that is handled by a lambda with the following code:
this.Loaded += (o, e) => {
// code
}
You've defined a method handling the Loaded event anonymously (it doesn't have a name) by using a lambda expression. It would read as "o, e goes to ... method definition with foo."
This is the "lambda operator", and you read it as "goes to". Say you had the statement:
doSomething(x => x + " hi");
You can replace the "=>" in your mind with this:
doSomething(delegate (string x) { return x + " hi" });
As you can see, it offers a heck of a shorthand. The compiler figures out the type of the variable that you're passing, and allows you to get rid of the function signature and bracketing for the code that you're passing the signature variables into.
It's a lambda operator, part of a lambda expression.
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."
It's syntax to declare an anonymous function, known in C# as a "lambda expression."
For example, (int p) => p * 2 represents a function that takes an integer and multiplies it by two.