First, I would like to ask you a question: give you a lot of names, let you find out the person with the last name, useProgram.
This program can be implemented in many ways. In this blog, we use the delegate and lambda expressions.
First, put all the names in a collection.
List <string> List = new list <string> {"Tian santao", "Liu qihan", "Zhang xiaoxuan", "Tian shengtong", "Wen xiaotong ", "Liu qihan", "Tian youqiao", "Wen Jia Shan", "Bai Tian Tong", "Liao zimian", "Zhang zefei", "Tian zanxin "};
Then, use the list <t> findall (predicate <t> match) method to find all strings that match the surname "Tian. Predicate <t> is a method delegate. If the object passed to it matches the condition defined in the delegate, the method returns true. The elements of the current list <t> are passed to the predicate <t> delegate one by one. elements that meet the conditions are stored in the returned list <t>.
Next I will use the C #1.0, C #2.0, C #3.0 methods to complete our program.
C #1.0
First define a static method,CodeAs follows:
Public static bool ismatch (string s) {return S. indexof ("Tian") = 0 ;}
Call list. findall (ismatch) to find all strings with the last name "Tian.
C #2.0
Directly write the following code:
List. findall (delegate (string s) {return S. indexof ("Tian") = 0 ;});
C #3.0, Lambda expression
The format is as follows:
List. findall (S => S. indexof ("Tian") = 0 );
Complete program code:
class program {static void main (string [] ARGs) {list
List = new list
{"Tian santao", "Liu qihan", "Zhang xiaoxuan", "Tian shengtong", "Wen xiaotong ", "Liu qihan", "Tian youqiao", "Wen Jia Shan", "Bai Tian Tong", "Liao zimian", "Zhang zefei", "Tian zanxin "}; // C #1.0 // list
result = List. findall (ismatch); // C #2.0 // list
result = List. findall (delegate (string s) // {// return S. indexof ("Tian") = 0; //}); // C #3.0 list
result = List. findall (S => S. indexof ("Tian") = 0); foreach (VAR item in result) {console. writeline (item) ;}} public static bool ismatch (string s) {return S. indexof ("Tian") = 0 ;}
compared with the implementation of C #1.0, C #2.0, and C #3.0 programs, we found that C # is becoming more and more human-oriented.