C # List <T> usage
Namespace: using System. Collections. Generic;
The List <T> class is the generic equivalent class of the ArrayList class. This class implements the IList <T> generic interface using an array that can be dynamically increased as needed.
The advantage of generics: it increases the efficiency and flexibility for compiling Object-oriented Programs in c # language. It does not forcibly pack or unbox the value type, or forcibly convert the reference type downward, so the performance is improved.
I. basic and common methods of List:
1. List <T> mList = new List <T> ();
A. T is the element type in the list. Now the string type is used as an example.
For example, List <string> mList = new List <string> ();
B. Add element: List. Add (T item) Add an element
For example, mList. Add ("laiyanbin ");
C. Insert element: Insert (int index, T item); add an element to the index position
For example, mList. Insert (1, "laiyanbin ");
D. Delete element: List. Remove (T item) delete a value
For example, mList. Remove ("laiyanbin ");
List. RemoveAt (int index); Delete the element whose subscript is index.
For example: mList. RemoveAt (0 );
List. RemoveRange (int index, int count); Delete count elements starting from subscript index
For example: mList. RemoveRange (3, 2); // an error occurs when the deletion range is exceeded.
Note: After an element is deleted, its subscripts automatically follow up.
E. Check whether List: List. Contains (T item) exists. The returned result is true or false.
F. Sort: List. Sort () // by default, the first letter of the element is in ascending order.
Reverse the order of elements in the List:
List. Reverse () // you can use it with List. Sort () to achieve the desired effect.
Traverse the elements in the List:
The type of foreach (T element in mList) T is the same as that of mList declaration.
{
Console. WriteLine (element );
}
G. List Clear: List. Clear ()
For example, mList. Clear ();
H. Obtain the number of elements in the List:
List. Count () returns the int value.
I. add the array to List: string [] temArr = {Ha "," Hunter "," Tom "," Lily "," Jay "," Jim "," Kuku ", "" Locu "};
MList. AddRange (temArr );
2. List <T> testList = new List <T> (IEnumerable <T> collection );
Create a List using a set as the parameter
E. g.: string [] temArr = {"Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu "};
List <string> testList = new List <string> (temArr );
3. List and array Conversion
1. Convert string [] to List <string>
Example: string [] str = {"1", "2 "};
List <string> list = new List <string> (str );
2. Convert from List <string> to string []
Example: List <string> list = new List <string>;
String [] str = list. ToArray ();
// Convert ViewState ["idlist"] to List <>
List <int> idlist = (List <int>) ViewState ["idlist"]