Differences between Lambda expressions and lambda statements in lambda expressions
Lambda expressions can be divided into lambda expressions and lambda statements.
Expression lambda: The lambda expression at the right of the => operator is called the expression lambda.
(Input parameters) => expression // expression lambda
For example
(x, y) => x == y
Statement lambda: => The right side of the operator is a statement block. The statement is contained in braces.
(Input parameters) =>{ statement;} // statement lambda
For example:
(x, y) => {return x == y;}
In addition to writing differently, are there any differences between the two? Use the following code for testing:
Using System; using System. collections. generic; namespace LinqTest {class Program {static void Main (string [] args) {List <int> list = new List <int> {1, 3, 2, 4 }; var resultUsingExpressionLambda = list. findAll (p => p <3); Console. writeLine ("use expression lambda:"); foreach (var item in resultUsingExpressionLambda) {Console. writeLine (item);} var resultUsingStatementLambda = list. findAll (p = >{ return p <3 ;}); Console. writeLine ("use statement lambda:"); foreach (var item in resultUsingStatementLambda) {Console. writeLine (item );}}}}
The code is relatively simple, that is, use the expression lambda and the statement lambda to find the number less than 3, and then output it. The result is as follows:
Using System; using System. collections. generic; namespace LinqTest {class Program {static void Main (string [] args) {List <int> list = new List <int> {1, 3, 2, 4 }; var resultUsingExpressionLambda = list. findAll (p => p <3); Console. writeLine ("use expression lambda:"); foreach (var item in resultUsingExpressionLambda) {Console. writeLine (item);} var resultUsingStatementLambda = list. findAll (p => {Console. writeLine (p); // This is the newly added return p <3 ;}); Console. writeLine ("use statement lambda:"); foreach (var item in resultUsingStatementLambda) {Console. writeLine (item );}}}}
Check the decompiled code.
Expression <Func <int, int, int> expression = (a, B) => a + B; // correct Expression <Func <int, int, int> expression1 = (a, B) => {return a + B ;}; // error. The lambda expression with the statement body cannot be converted to the expression tree.