Dùng method Clear():
List<string> myList = new List<string>() { "one", "two", "three", "four", "five", "six" };
myList.Clear();
Ví dụ
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> myList = new List<string>()
{ "one", "two", "three", "four", "five", "six" };
foreach (string str in myList) Console.WriteLine(str);
Console.WriteLine("Số phần tử: " + myList.Count); // 6
myList.Clear();
Console.WriteLine("Số phần tử sau Clear(): " + myList.Count); // 0
}
}
Kết quả
one two three four five six Số phần tử: 6 Số phần tử sau Clear(): 0
Lưu ý:
Clear()xóa tất cả phần tử, Capacity không đổi (vẫn cấp phát bộ nhớ)TrimExcess()sau Clear() để giảm Capacity- Gán
nullhoặcnew List<T>()tạo list mới, GC sẽ dọn list cũ