A Brief Introduction to Lambda expressions
In. NET 1.0, we all know that we often use delegation. With delegation, we can transfer methods like passing variables. In a certain program, delegation is a powerful type of hosting method, which was also widely used at the moment, however, in general, delegated use is still cumbersome. Take the following steps to use a delegate:
Use the delegate keyword to create a delegate, including declaring the return value and parameter type.
To receive this delegate.
Create the instance of this delegate and specify a method that matches the return value and parameter type to pass the previous
Okay, I admit that I saw the above on the Internet, but it is a good introduction to delegation. If you want to use delegation before, you must go through the three steps below, in my opinion, it is really complicated, so a Lambda expression is introduced in the topic. It can bypass Step 2 through an anonymous method, so I only need to define a delegate, use Lambda expressions to implement delegation. Let's take a look at the following small example:
// The Compiler does not know what is next, so we cannot use the var keyword here.
Action dummyLambda = () => { Console.WriteLine("Hello World from a Lambda expression!"); }; // double y = square(25);Func<double, double> square = x => x * x; // double z = product(9, 5);Func<double, double, double> product = (x, y) => x * y; // printProduct(9, 5);Action<double, double> printProduct = (x, y) => { Console.WriteLine(x * y); }; // var sum = dotProduct(new double[] { 1, 2, 3 }, new double[] { 4, 5, 6 });Func<double[], double[], double> dotProduct = (x, y) =>{ var dim = Math.Min(x.Length, y.Length); var sum = 0.0; for (var i = 0; i != dim; i++) sum += x[i] + y[i]; return sum;}; // var result = matrixVectorProductAsync(...);Func<double, double, Task<double>> matrixVectorProductAsync = async (x, y) =>{ var sum = 0.0; /* do some stuff using await ... */ return sum;};
From the code above, we can see that:
If there is only one parameter, no need to write ()
If there is only one execution statement and we want to return it, no {} is required and no return is required.
Lambda can be executed asynchronously, as long as the async keyword is added to the front.
The Var keyword cannot be used in most cases.
The above is all the content of this article. I hope you will like it.