1. namespace:
System. Collections. Generic (Assembly: mscorlib)
2. Description:
1) indicates the list of objects that can be accessed through indexes. It provides methods for searching, sorting, and operating the list.
2) is the generic equivalent class of the ArrayList class.
3) You can use an integer index to access the elements in this set. The index starts from scratch.
4) can receive null references (in VBNothing).
5) Allow repeated Elements
3. Creation and initialization:
List <string> myList = new List <string> (); // The initial Capacity is zero.
List <string> myList2 = new List <string> (30); // The initial Capacity is 30.
List <string> myList3 = new List <string> (new string [] {"1", "a", "2", "B "}); // The initial Capacity is 4 and the element has been copied
4. Capacity and Count
1) the number of elements that can be stored before the Capacity needs to be adjusted; Count the number of actually stored elements.
2) Capacity is always greater than or equal to Count
View the effect of the add () method on Capacity and Count using Reflector:
In List <T>:
Private T [] items;
Private int _ size;
Public int Count {
Get {
Return this. _ size;
}
}
Public int Capacity
{
Get {
Return this. _ items. Length;
}
Set {
//......
}
}
When we call the Add method to Add elements, the internal implementation is:
Public void Add (T item)
{
If (this. _ size = this. _ items. Length)
{
This. EnsureCapacity (this. _ size + 1); // expand Capatity
}
This. _ items [this. _ size ++] = item;
//.......
}
Private void EnsureCapacity (int min)
{
If (this. _ items. Length <min)
{
Int num = (this. _ items. Length = 0 )? 4: (this. _ items. Length * 2 );
If (num <min)
{
Num = min;
}
This. Capacity = num;
}
}
So far, the similarities and differences between Capacity and Count are clear at a glance.
The TrimExcess method can make Capacity equal to Count;
Internal Implementation of TrimExcess:
Public void TrimExcess ()
{
Int num = (int) (this. _ items. Length * 0.9 );
If (this. _ size <num)
{
This. Capacity = this. _ size;
}
}
Here, we can also understand this sentence on MSDN: "If the list is greater than 90% of the capacity, the TrimExcess method will not perform any operations ".
5. Traverse elements:
Foreach (string s in myList)
{
Console. WriteLine ("El: {0}", s );
}
6. Insert an element By Insert:
MyList. Insert (index, "VB"); // Insert it to the specified index (index cannot be greater than Capacity-1)
7. Remove element By Remove:
MyList. Remove ("C #"); // Remove the first matching item of a specific object. If there are two "C #", Remove one with a small index.