This article involves:
1. Perform "batch type conversion" on the elements in the list"
2. "processing" for each element in the list"
3. Sort list elements
4. Check whether the element in the list meets a certain condition.
5. Search for elements in the list
Note: The preceding operations are not aimed at arrays or lists... but are universal. Generally, the list that implements the ienumerable <t> interface can have the following methods.
1. Perform "batch type conversion" on the elements in the list"
In some cases, all the elements in the list may need to be converted to another type. This can be achieved by calling the convertall method.
PublicList <toutput> convertall <toutput> (
Converter <t, toutput> Converter
)
The 2nd parameter of the preceding method is a delegate, which is defined as follows:
PublicList <toutput> convertall <toutput> (converter <t, toutput> converter );
By designing an array element type conversion method that meets the requirements of this delegate, the convertall method can convert all elements in a set and then copy them to a new set.
ExampleCode:
Convertall method sample code
Using System;
Using System. Collections. Generic;
Public Class Example
{
Public Class Pointf
{
Public Pointf ( Float X1, Float Y1)
{
This . X1 = x1;
This . Y1 = Y1;
}
Public Float X1;
Public Float Y1;
}
Public Class Point
{
Public Point ( Int X2, Int Y2)
{
This . X2 = x2;
This . Y2 = Y2;
}
Public Int X2;
Public Int Y2;
}
Public Static Void Main ()
{
List <pointf> LPF = New List <pointf> ();
LPF. Add ( New Pointf ( 27.8f , 32.62f ));
LPF. Add ( New Pointf ( 99.3f , 147.273f ));
LPF. Add ( New Pointf ( 7.5f , 1412.2f ));
Console. writeline ();
Foreach (Pointf P In LPF)
{
Console. writeline (P. x1.tostring () + " " + P. y1.tostring ());
}
// Call Method 1: Standard writing
List <point> Lp = LPF. convertall (
New Converter <pointf, point> (pointftopoint ));
// Call Method 2: Use the anonymous method (you can save the pointftopoint method defined separately)
// Note that when using anonymous methods, the method body is headers with the delegate keyword,
// The parameter list is followed by the method code written in a pair of braces and ended with a semicolon.
List <point> lp2 = LPF. convertall (
New Converter <pointf, point> (
Delegate (Pointf PF)
{
Return New Point (( Int ) PF. X1 ,( Int ) PF. Y1 );
}));
// Method 3: Use lambda expressions to streamline code again
List <point> lp3 = LPF. convertall (
New Converter <pointf, point> (
(PF) => { Return New Point (( Int ) PF. X1 ,( Int ) PF. Y1 );}));
Console. writeline ();
Foreach (Point P In LP)
{
Console. writeline (P. x2.tostring () + " " + P. y2.tostring ());
}
Console. readkey ();
}
// A conversion method is defined here, which corresponds to the converter delegate. We can call this method "element converter"
Public Static Point pointftopoint (pointf PF)
{
Return New Point ((( Int ) PF. X1 ),(( Int ) PF. Y1 ));
}
}
/* This code example produces the following output:
{X = 27.8, y = 32.62}
{X = 99.3, y = 147.273}
{X = 7.5, y = 1412.2}
{X = 27, y = 32}
{X = 99,y = 147}
{X = 7, y = 1412}
*/
The converter delegate is a system delegate in the C # system namespace, which is mainly used to convert element types.
2. "processing" for each element in the list"
Generally, we will write a foreach loop to process the elements in the set one by one, but this causes low code readability. In fact,. NET provides the foreach <t> Method for us.
The method is prototype as follows:
Public VoidForeach (
Action <t> action
)
Its parameter is an action delegate that references the "processing method" that is "applied to" each array element ".
Sample Code:
Foreach method example
Using System;
Using System. Collections. Generic;
Class Program
{
Static Void Main ()
{
List <string> names = New List <string> ();
Names. Add ( " Bruce " );
Names. Add ( " Alfred " );
Names. Add ( " Tim " );
Names. Add ( " Richard " );
// The print method is called to list each element cyclically.
// Call method 1
Names. foreach (print );
// Call Method 2: anonymous method
Names. foreach ( Delegate (String name)
{
Console. writeline (name );
});
// Method 3: Use a Lambda expression to streamline the code and omit the print method.
Names. foreach (r => console. writeline (R ));
Console. readkey ();
}
Private Static Void Print ( String S)
{
Console. writeline (s );
}
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
Iii. Sorting list elements
The diaries before sorting the set are recorded. For more information, see the previous diary.
Here is a summary:
On msdn, list has the following sort overload:
If you call the sort () method without parameters, the elements in the set must implement the system. icomparable interface. Otherwise, an invalidoperationexception is thrown.
If the element of the set does not implement the icomparable interface, you can call sort (icomparer <t>). In this case, we need to create a class to implement the icomparer interface as the comparator to complete the sorting.
Or it is simpler. You don't need to define a comparator. simply provide a method for the sort method to "compare two objects"-implement comparison <t> delegation.
Comparison delegate sample code
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Sortobjectarray
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Myclass [] objs = New Myclass [ 10 ];
Random ran = New Random ();
For ( Int I = 0 ; I < 10 ; I ++)
Objs [I] = New Myclass {value = ran. Next ( 1 , 100 )};
Comparison <myclass> whoisgreater = Delegate (Myclass X, myclass y)
{
If (X. value> Y. value)
Return 1 ;
Else
If (X. value = Y. value)
Return 0 ;
Else
Return - 1 ;
};
Array. Sort <myclass> (objs, whoisgreater );
Array. foreach <myclass> (objs, (OBJ) =>{ console. writeline (obj. Value );});
Console. readkey ();
}
}
Class Myclass
{
Public Int Value;
}
}
4. About prddicate <t> Delegation
This delegate can be used to implement many implementations, such:
A. Check whether the element in the list meets a condition trueforall <t>
B. Search for the element exists in the set <t>
C. Find the element that meets the conditions <t> findlast <t> findall <t>
D. Search for the findindex index of the element that meets the condition.
... And so on
If the collection
Each element in matches the condition defined by the specified predicate.TrueOtherwiseFalse. If the list does not contain any elements, the returned value isTrue.
Predicate <t> is a delegate that references a method that returns the bool value. This method represents the conditions that must be met by the collection element.
Sample Code
Using System;
Using System. Collections. Generic;
Public Class Example
{
Public Static Void Main ()
{
List < String > Din1_urs = New List < String > ();
Dinosaurs. Add ( " Compsognathus " );
Dinosaurs. Add ( " Amargasaurus " );
Dinosaurs. Add ( " Oviraptor " );
Dinosaurs. Add ( " Velociraptor " );
Dinosaurs. Add ( " Deinonychus " );
Dinosaurs. Add ( " Dilophosaurus " );
Dinosaurs. Add ( " Gallimimus " );
Dinosaurs. Add ( " Triceratops " );
Console. writeline ();
Foreach (String Dinosaur In Dinosaurs)
{
Console. writeline (dinw.ur );
}
Console. writeline ( " \ Ntrueforall (endswithsaurus): {0} " ,
Dinosaurs. trueforall (endswithsaurus ));
Console. writeline ( " \ Nfind (endswithsaurus): {0} " ,
Dinosaurs. Find (endswithsaurus ));
Console. writeline ( " \ Nfindlast (endswithsaurus): {0} " ,
Dinosaurs. findlast (endswithsaurus ));
Console. writeline ( " \ Nfindall (endswithsaurus ): " );
List < String > Sublist = dinosaurs. findall (endswithsaurus );
Foreach (String Dinosaur In Sublist)
{
Console. writeline (dinw.ur );
}
Console. writeline (
" \ N {0} elements removed by removeall (endswithsaurus ). " ,
Dinosaurs. removeall (endswithsaurus ));
Console. writeline ( " \ NLIST now contains: " );
Foreach ( String Dinosaur In Dinosaurs)
{
Console. writeline (dinw.ur );
}
Console. writeline ( " \ Nexists (endswithsaurus): {0} " ,
Dinosaurs. exists (endswithsaurus ));
}
// Search predicate returns true if a string ends in "Saurus ".
Private Static Bool Endswithsaurus (string S)
{
If (S. length> 5 )&&
(S. substring (S. Length- 6 ). Tolower () = " Saurus " ))
{
Return True ;
}
Else
{
Return False ;
}
}
}
/* This code example produces the following output:
Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops
Trueforall (endswithsaurus): false
Find (endswithsaurus): amargasaurus
Findlast (endswithsaurus): Dilophosaurus
Findall (endswithsaurus ):
Amargasaurus
Dilophosaurus
2 elements removed by removeall (endswithsaurus ).
List now contains:
Compsognathus
Oviraptor
Velociraptor
Deinonychus
Gallimimus
Triceratops
Exists (endswithsaurus): false
*/