On the Understanding of Lambda Expression

  • 2021-06-29 10:46:24
  • OfStack

At.NET 1.0, we all know that delegation is what we often use.With delegates, we can pass variables like 1.In some programs, delegation is a strong type of managed method pointer, which was once used by us extensively. But in general, delegation is still a bit cumbersome to use.Take a look at the following steps to use a delegate 1:

Create a delegate with the delegate keyword, including declaring return values and parameter types
Receive this delegation where it is used
Create an instance of this delegate and specify a method that matches the return value and parameter type to pass to the past
Okay, I admit it's what I saw on the Internet, but it's a good introduction to delegation. In the past, to use delegation, you had to go through the three steps above. I think it's really complicated, so the theme comes with an Lambda expression, which can bypass Step 2 anonymously, so I just need to define one delegation.Then use the Lambda expression to implement delegation, let's write a small example below:
//The compiler doesn't know what's behind it, so we can't 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 you only have one parameter, you do not need to write ()
If there is only one execution statement and we want to return it, we don't need {} and we don't need to write return
Lambda can be executed asynchronously as long as the async keyword is preceded by it
The Var keyword is not available in most cases

The above is the whole content of this article, I hope you like it.


Related articles: