[C #] C # knowledge Review,
C # knowledge Review-Lambda
Lambda expressions
Lambda statements
Asynchronous Lambda
Use Lambda in LINQ
Type inference in Lambda
Use range of variables in Lambda
Lambda features
Lambda Introduction
Lambda expressions are simplified anonymous functions that can be used to create a delegate or expression directory tree. Second, you can also pass the Lambda expression as a parameter, or apply it to a function returned after the function call value is called. Lambda expressions are often used in LINQ.
Simple syntax for creating a Lambda expression: input parameter => expression or statement block. Where, => is the Lambda operator and can be read as "goes ".
delegate int MyDel(int x); static void Main(string[] args) { MyDel myDel = x => x++; var j = myDel(5); }
Create Expression Tree:
Expression<MyDel> myDel = x => x++;
=>Operators and = operators (Value assignment operators) have the same priority and are all right-combined operations.
Lambda expressions, such as Where <TSource> parameters, are often used in LINQ queries. This method has multiple reloads. Only one of them is listed here.
1 // 2 // Summary: 3 // a predicate-based filtering value sequence. 4 // 5 // parameter: 6 // source: 7 // System. Collections. Generic. IEnumerable to be filtered <T>. 8 // 9 // predicate: 10 // function used to test whether each element meets the conditions. 11 // 12 // type parameter: 13 // TSource: 14 // type of the element in source. 15 // 16 // return result: 17 // a System. Collections. Generic. IEnumerable <T> that contains elements that meet the conditions in the input sequence. 18 // 19 // exception: 20 // System. ArgumentNullException: 21 // source or predicate is null. 22 public static IEnumerable <TSource> Where <TSource> (this IEnumerable <TSource> source, Func <TSource, bool> predicate );
The parameter is the delegate type Func <TSource, bool> predicate). Here we use a Lambda expression to create it. I think it should be the most appropriate. Also, if the parameter type is System of the abstract class. linq. expressions. expression <Func>, where the Func delegate is overloaded with sixteen parameters. You can also use Lambda expressions to create the corresponding Expression Tree.
[Note] Lambda expressions are not allowed on the left side of the is or as operator.
Lambda expressions
The expression is on the right of the => operator and is called "lambda expression ". Lambda expressions are commonly used in LINQ and build expression trees, and can also return results.
Basic Format: (input parameter) => expression.
For example:
( ) => true;
x => x == 1; (x) => x == 1; (x, y) => x == y;
[Note] When a lambda expression has only one input parameter, brackets ("()") are optional. Separate multiple input parameters with commas.
You can also choose to explicitly specify the type, generally only when the compiler is difficult or cannot accurately infer the input type.
Func<int, int, bool> func = (int x, int y) => x == y;
Null parentheses ("()") are used to specify zero input parameters. A Lambda subject can contain one or more methods for calling.
() => YourMethod()
Compared with the preceding Lambda expression, a lambda statement only contains braces ("{}").
Basic Format: (input parameter) =>{ expression }.
The body of a lambda statement can be composed of any number of common statements. However, we usually write a few statements (about three statements ).
delegate void MyDel(string s); // ...MyDel myDel = n => { var s = n + " Fanguzai!"; Console.WriteLine(s); }; myDel("Hi,");
Asynchronous Lambda
Through async and await keywords, we can easily and quickly create lambda expressions and statements that contain asynchronous processing. The blogger has published about eight articles about Asynchronization. You can click to enter the directory.
Here, I use a simple asynchronous call method to compile the click event triggered by the execution button, that is, call the Asynchronous Method.DoAsync.
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { await DoAsync(); } async Task DoAsync() { await Task.Delay(250); } }
Now, simplify the Click Event and add async.
public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += async (sender, e) => { await DoAsync(); }; } async Task DoAsync() { await Task.Delay(250); } }
Use Lambda in LINQ
Many parameters in LINQ are delegate-type parameters, such as Func <T, effectresult>, which can define input parameters and return types. The blogger has published many articles about LINQ. You can also click to enter the directory.
public delegate TResult Func<TArg0, TResult>(TArg0 arg0)
Func <int, bool> indicates that int Is the input parameter and bool is the return value.
Func <int, int, bool> indicates that two int values are input parameters, and one bool value is returned.
Example:
Func<int, bool> myFunc = x => x == 250; var result = myFunc(1314);
The C # compiler can automatically infer the type of input parameters. You can specify multiple input parameters explicitly.
var nums = new[] { 2, 5, 0 }; var query = nums.Count(x => x > 2); var query2 = nums.Count<int>(x => x < 2);
[Note] Do not confuse => and> =. The former is the Lambda operator, and the latter is the arithmetic comparison operator.
Type inference in Lambda
The compiler will deduce the type of Lambda Based on the Lambda subject, the delegate type of the parameter, the C # language specification, and other factors.
Use range of variables in Lambda
We can reference variables out of the scope in the Lambda body. For example:
Var nums = new [] {2, 5, 0}; // int [] type var compareNum = 2.5; var query = nums. count (x => x = compareNum );
Lambda features
The number of input parameters in Lambda must be the same as the number of parameters in the delegate type.
Each input parameter in Lambda must be implicitly converted to its corresponding delegate parameter type.
The return value (if any) in Lambda must be implicitly converted to the return type of the delegate.
C # basic Review Series
C # knowledge Review-serialization
C # knowledge Review-Expression Tree Expression Trees
C # knowledge Review-feature Attribute and AssemblyInfo. cs-understanding common feature attributes
C # knowledge Review-delegated delegate and C # knowledge Review-delegated delegate (continued)
C # knowledge Review-Introduction to events and C # knowledge Review-Event Events
There is no unspeakable secret between the string, the String, the big S, and the small S
C # knowledge Review-do you really understand exceptions?
Have you ever understood the entry function Main? Using batch processing to convert the Main function
C # basic review-anonymous method
Error Correction
@ Likeheart: "half a year's life"-> "half a life ". For details, see comment area 10L.
[Blogger] Anti-Bot
Http://www.cnblogs.com/liqingwen/p/6216582.html.
[Reference] Microsoft official documentation