List<T> có 2 thuộc tính quan trọng: Count (số phần tử thực tế) và Capacity (dung lượng mảng nội bộ).
Ví dụ minh họa
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List();
list.Add("Accessories");
list.Add("Clothing");
list.Add("Footwear");
Console.WriteLine($"Count (số phần tử): {list.Count}"); // 3
Console.WriteLine($"Capacity (dung lượng mảng): {list.Capacity}"); // 4 (tự động mở rộng)
// Thêm thêm để thấy Capacity thay đổi
list.Add("Watches");
list.Add("Bags");
Console.WriteLine($"\nSau khi thêm 2 phần tử:");
Console.WriteLine($"Count: {list.Count}"); // 5
Console.WriteLine($"Capacity: {list.Capacity}"); // 8 (gấp đôi)
// Trim excess
list.TrimExcess();
Console.WriteLine($"\nSau TrimExcess():");
Console.WriteLine($"Count: {list.Count}"); // 5
Console.WriteLine($"Capacity: {list.Capacity}"); // 5
}
}
Kết quả đầu ra
Count (số phần tử): 3 Capacity (dung lượng mảng): 4 Sau khi thêm 2 phần tử: Count: 5 Capacity: 8 Sau TrimExcess(): Count: 5 Capacity: 5
Lưu ý quan trọng: Count = số phần tử thực tế (dùng để lặp, truy xuất). Capacity = bộ nhớ đã cấp phát (tối ưu hiệu năng, tránh resize liên tục). Khái niệm "size" trong bài gốc nhầm lẫn Capacity với Count.