Predicate is widely used in set search and WPF data binding. Its calling format is as follows:
Call method: predicate <Object> (method)/predicate <parameter type> (method)
1. <> it indicates generic and can accept parameters of any type.
2. The (method) method can be passed as a parameter, indicating a delegate.
3. The return type is bool, indicating success or failure.
In an example, find a specific item in emplist:
Class Employee { Private String _ Firstname; Private String _ Lastname; // Private int _ empcode; Private String _ Designation; Public Employee (){} Public Employee ( String Firstname, String Lastname, String Designation) {_ firstname = Firstname; _ lastname =Lastname; _ designation = Designation ;} /// <Summary> /// Property first name /// </Summary> Public String Firstname { Get { Return _ Firstname ;} Set {_ Firstname = Value ;}} /// <Summary> /// Property last name /// </Summary> Public String Lastname { Get { Return _ Lastname ;} Set {_ Lastname =Value ;}} Public String Designation { Get { Return _ Designation ;} Set {_ Designation = Value ;}} 1. Traditional Methods
Define a search method:
Static BoolEmpsearch (employee EMP ){If(EMP. firstname ="Anshu")Return True;ElseReturn False;}
Using the generic find () method, find () automatically calls the empsearch method iteratively.
Predicate <employee> Pred =NewPredicate <Employee (empsearch); employee EMP= Emplist. Find (Pred );
2. Use the anonymous method
EMP = emplist. Find (Delegate(Employee e ){If(E. firstname ="Anshu")Return True;ElseReturn False;});
You do not need to explicitly define a method,CodeMore concise
3. Use lambda expressions
EMP =NewEmployee (); EMP= Emplist. Find (e) => {Return(E. firstname ="Anshu");});
(E) => indicates passing a parameter. The parameter type can be automatically parsed.
4. search list
List <employee> employees =NewList <employee>(); Employees= Emplist. findall (e) => {Return(E. firstname. Contains ("J"));});
5. Search Indexes
Narrow the search scope by specifying the number of start indexes and search entries
IntIndex = emplist. findindex (0,2, (E) => {Return(E. firstname. Contains ("J"));
Indicates that two entries are searched from index 0.
6. list commonly used comparator Delegation
Sort the following Arrays
VaR Data = New List < Int > (); VaR Rand = New Random (); console. writeline ( " Unsorted list " ); For ( Int I = 0 ; I < 10 ; I ++ ){ Int D = Rand. Next ( 0 , 100 ); Data. Add (d); console. Write ( " {0} " , D );}
Use lampda to sort data in ascending order
Data. Sort (E1, E2) => {ReturnE1.compareto (E2 );});