Lambda expressions (basic concepts)

Source: Internet
Author: User
Tags variable scope

C # Lambda expressions is used in data deletion operations during development. If you are learning the function of writing data to SQL, therefore, we recommend that you understand C # Lambda expressions so that they can be correctly used during operations.

C # What is lambda expressions? We will encounter this operation when processing database data deletion operations. What is the specific C # Lambda expressions and its meaning and usage? Next let's take a look at the specific content.

1. About C # Lambda expressions:

A Lambda expression is an anonymous function that contains several expressions and statements. Can be used to create a delegate object or expression tree type. All lambda expressions use the operator "=>" to represent "goes )". The left part of the operator is the input parameter table, and the right part is the expression or statement block. X => x converts X to X by X ". Lambda can be assigned to a delegate type:

C # Lambda instance 1:

 
 
  1. delegate int del(int i);  
  2.  
  3. del myDelegate = x => x * x;  
  4.  
  5. int j = myDelegate(5); //j = 25  

It can also be used to create an Expression Tree Type:

C # Lambda instance 2:

 
 
  1. using System.Linq.Expressions;  
  2.  
  3. //…  
  4.  
  5. Expression<del> = x => x *x;  

The operator "=>" has the same computing priority as "=" and is right-related (executed first on the right ).

In example 1, we noticed that the delegate definition contains an input parameter of the int type and the return value of the int type. There is no declaration of any type in the lambda expression in the example. Yes, the compiler has implemented implicit data type conversion for us: the input parameter type can be implicitly converted from the input parameter type of the delegate, and the return type can be implicitly converted to the delegate return type.

Lambda statements cannot appear as the left operands of the "is" and "as" operators. That is

 
 
  1. del myDelegate = x => x * x as string;  //error 

All constraints on anonymous methods also apply to Lambda. See anonymous methods (C # programming guide ).

2. Understand C # Lambda expressions from expressions

A Lambda expression composed of a computing expression is called an expression lambda. Expression Lambda is often used to construct an Expression Tree. A Lambda expression returns the result of the computation expression. The basic structure is as follows:

 
 
  1. (Input parameters) => Expression
  2.  
  3. // If there is only one input parameter, brackets can be omitted.
  4.  
  5. // If more than one input parameter exists, brackets must be added.
  6.  
  7. (X) => X * X equals X => X * x
  8.  
  9. (X, y) => X = y
  10.  
  11. // You can explicitly specify the type of the input parameter
  12.  
  13. (Int x, string S) => S. length> X
  14.  
  15. // You can also leave no input parameters
  16.  
  17. () => Somemethod1 ()

The above code calls a method in Lambda. It should be noted that when creating an Expression Tree that will be used by others, it is not appropriate to execute method calls in Lambda. For example, execute in SQL Server.

In general, it is meaningless or impossible to let a method be executed outside the originally designed context environment.

3. Understand C # Lambda expressions from statements

Statement Lambda is very similar to expression lambda, but the statement is contained in braces:

 
 
  1. (input parameters) => {statement;} 

The statements in braces can be any number of rows or multiple rows (define a Lambda statement that defines an anonymous method ):

 
 
  1. TestDelegate myDel = n => { string s = n + " " + "World";   
  2.  
  3. Console.WriteLine(s); };  

Of course, statements lambda, like anonymous methods, cannot be used to create expression trees.

4. C # Lambda expressions type Prediction

When writing a Lambda statement, we usually do not need to specify the type of the input parameter. The compiler guesses the type based on The Implementation of The Lambda body and the definition of the delegate.

For example, if you want to delete an element smaller than 100 from a list <int>

 
 
  1. Lst. removeall (I => I <100); // I will be guessed as int

The general rules for guessing are as follows::

◆ Lambda must contain the same number of input parameters as the delegate definition;

◆ Each Lambda input parameter must be implicitly converted to the input parameter required in the delegate definition;

◆ The lambda return value must be implicitly converted to the return value in the delegate definition.

Note: Currently, there is no "Lambda type" type in the common type system. If "Lambda type" is mentioned in some cases, it usually indicates the delegate definition or expression <> type.

5. C # Lambda expressions variable scope

External variables can be referenced in Lambda definitions. Any variables that can be accessed at the definition can be referenced in Lambda.

A Lambda definition defines an anonymous method and generates a delegate object. The reference of external variables will be "captured" inside the delegate object, and will be accompanied by the entire life cycle of the delegate object. This variable will not be garbage collected until the life cycle of the delegate object ends. Even if the external variables have exceeded the original scope, they can still be used in Lambda. All referenced external variables must be explicitly assigned values before Lambda definitions. See the following example.

 
 
  1. Delegate bool D ();
  2. Delegate bool D2 (int I );
  3. Class Test
  4. {
  5. D del;
  6. D2 del2;
  7. Public void testmethod (INT input)
  8. {
  9. Int J = 0;
  10. // Initialize the delegates with Lambda expressions.
  11. // Note access to 2 outer variables.
  12. // Del will be invoked within this method.
  13. Del = () => {J = 10; return j> input ;};
  14.  
  15. // Del2 will be invoked after testmethod goes out of scope.
  16. Del2 = (x) => {return x = J ;};
  17. // Demonstrate value of J:
  18. // Output: J = 0
  19. // The delegate has not been invoked yet.
  20. Console. writeline ("J = {0}", J );
  21. // Invoke the delegate.
  22. Bool boolresult = del ();
  23. // Output: J = 10 B = true // note that J is modified during del execution
  24. Console. writeline ("J = {0}. B = {1}", J, boolresult );
  25. }
  26. Static void main ()
  27. {
  28. Test test = new test ();
  29. Test. testmethod (5 );
  30. // Prove that del2 still has a copy
  31. // Local variable J from testmethod.
  32.  
  33. // The reference of J exceeds the scope defined previously.
  34. Bool result = test. del2 (10 );
  35. // Output: True
  36. Console. writeline (result );
  37. Console. readkey ();
  38. }
  39. }
  40.  

The following are the rules on variable scope:

◆ Variables that are "captured" will not be reclaimed before the end of the delegated lifecycle;

◆ Variables defined in Lambda are invisible to external users;

◆ Lambda cannot directly capture a parameter variable with ref or out descriptions;

◆ The return statement in Lambda does not result in the return of the current method;

◆ The lambda statement cannot contain the Goto, break, or continue statements that will cause the current execution range to jump.

6. C # Lambda expressions learning Summary

Lambda is another form of anonymous method. It can be used in some places to make the code more concise. Defining a lambda is essentially defining the implementation body of a delegate.

From blog: http://www.cnblogs.com/smwikipedia/archive/2009/05/06/1450825.html

C # Lambda expressions-related content will be introduced to you here, I hope you can understand and learn C # Lambda expressions, and then we will continue to learn some applications of C # Lambda expressions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.