List<T> là danh sách động (dynamic array) kiểu mạnh trong System.Collections.Generic.
Các cách khởi tạo:
- Rỗng rồi Add:
List<string> myList = new List<string>(); myList.Add("one"); myList.Add("two"); - Collection initializer (khuyến nghị):
List<string> myList = new List<string> { "one", "two", "three" }; - Với capacity ban đầu:
List<string> myList = new List<string>(100); // Tránh resize
Ví dụ
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> myList = new List<string>
{
"one", "two", "three", "four", "five", "size"
};
Console.WriteLine(myList.Count); // 6
}
}
Kết quả
6
Phương thức hay dùng: Add, AddRange, Insert, Remove, RemoveAt, Clear, Contains, Sort, Find, FindAll, ConvertAll.