A brief introduction to C# Lambda expressions

Lambda expressions can be seen as a quick way to define functions or delegates. It has the following two forms:

(input-parameters) => expression

(input-parameters) => { <sequence-of-statements> }

Here are two examples

Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
// Output:
// 25
Action<string> greet = name =>
{
    string greeting = $"Hello {name}!";
    Console.WriteLine(greeting);
};
greet("World");
// Output:
// Hello World!

In the first example, the two ints after func respectively represent the input parameter type and the return value type, square is the method name, x is the formal parameter, and x*x is the return value.

In the second example, the string behind Action indicates the input type, greet is the function name, and name is the formal parameter.

Guess you like

Origin blog.csdn.net/qq_43533956/article/details/124254782