Home >Backend Development >C#.Net Tutorial >Introduction to C# List
1 About the introduction
(1) Namespace: System.Collections.Generic
public class List
(2) The List
(3) Benefits of generics: It adds great efficiency and flexibility to writing object-oriented programs using the C# language. There is no forced boxing and unboxing of value types, or downcasting of reference types, so performance is improved.
(4) Performance Note: When deciding to use List
If you use a reference type for the type T of the List
(5) In Microsoft’s words:
“Any reference or value type added to the ArrayList will be implicitly upcast to Object. If the item is a value type, it must be cast when adding it to the list. Boxing, unboxing while retrieving, and boxing and unboxing all reduce performance; the impact of boxing and unboxing is significant when you have to iterate over a large collection. ."
Common methods
1 Statement:
(1)List
T is the type of elements in the list. Now take the string type as an example
For example: List< ;string> mList = new List
(2)List
Create a List with a collection as a parameter
string[ ] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };
List
2 Add element:
(1) List. Add(T item) Add an element
mList.Add("John");
(2) List. AddRange(IEnumerable
string[] temArr = { "Ha","Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };
mList. AddRange(temArr);
(3)Insert(int index, T item); Add an element at the index position
mList.Insert(1, "Hei");
Traverse the elements in the List:
foreach (T element in mList) The type of T is the same as when mList was declared
{
Console.WriteLine(element);
} as follows:
foreach (string s in mList)
{
Console.WriteLine(s);
}
2 Delete element
(1)List.Remove(T item) Delete a value
such as: mList.Remove("Hunter");
(2) List.RemoveAt(int index); Delete The element whose subscript is index
such as mList.RemoveAt(0);
(3) List. RemoveRange(int index, int count);
Start from the subscript index and delete count elements
such as mList.RemoveRange(3, 2);
3 Determine whether an element is in the List Medium:
List. Contains(T item) Returns true or false, very practical
if (mList.Contains("Hunter"))
{
Console.WriteLine("There is Hunter in the list");
}
else
{
mList.Add("Hunter");
Console.WriteLine("Add Hunter successfully.");
}
More introduction to C# List& lt ;T>For detailed usage information, please pay attention to the PHP Chinese website for related articles!