Day 13 of advanced learning

Catalog 1. Anonymous type 2. Lambda expression 1. Anonymous type Without indicating the type of type, an object of unknown type is created through im...
1. Anonymous type
2. Lambda expression

Catalog

1. Anonymous type

Without indicating the type of type, an object of unknown type is created through implicit type and object initializer, which reduces code

1. Define anonymous type object: it can only contain read-only properties and cannot be modified

var p = new; Console.WriteLine ("Full name:"+p.Name +"Age:"+p.Age);

2. Define an array of anonymous types:

var a = new [] { new, new, new,}; //Consistent type foreach (var item in a) { Console.WriteLine ("Full name:"+item.Name +"Age:"+item.Age);}

2. Lambda expression

It can be understood as an anonymous method, with = > parameter on the left and expression or statement block on the right. Closures can also be formed

1. Expression lambda 2. Statement lambda

public delegate int mydele(int a,int b); public delegate int mydele2(int a); public delegate void mydele3(); public delegate int mydele4(int a,string b); mydele tt =(x,y) =>x+y; //The type can be omitted and identified automatically according to the parameters mydele2 t2 =x=>++x; //When there is only one parameter, brackets are optional, and multiple parameters, brackets must be added mydele3 t3 =()=>; //Parentheses cannot be omitted when there is no parameter mydele4 t4 =(int x,string s) => s.Length >x; //Unable to determine type, to display the specified type

2. Standard input parameters

Func<int,int> d1= a => a + a; //Two parameters Console.WriteLine (d1(3)); Func<int ,int ,int> d2= (c,d)=>c+d; //Three parameters Console.WriteLine (d2(4,5)); Func<int ,int ,bool> d2= (c,d)=>c==d; //Three parameters Console.WriteLine (d2(4,5)); //Customize console.writeline (D3 (4)); true or false public delegate T mydelega<V,T>(T a); mydelega<int ,int> d3 = e => e * e; //Sort method using lambda expression size sort //Multi weight sorting, sorting by a rule according to the weight priority of the rule l.Sort((x, y) => x.sortByAge(y) * 4 + x.sortByChinese(y) * 2 + x.sortByMath(y)*1); public int sortByAge(Student anotherStudent) { int result = this.Age - anotherStudent.Age; return result == 0 ? 0 : (result > 0 ? 1 : -1); } public int sortByChinese(Student anotherStudent) { int result = (int)(this.Chinese - anotherStudent.Chinese); return result == 0 ? 0 : (result > 0 ? 1 : -1); }

3 December 2019, 23:28 | Views: 9459

Add new comment

For adding a comment, please log in
or create account

0 comments