Giới thiệu
StringCollection là tập hợp chuyên biệt cho chuỗi. Để xóa lần xuất hiện đầu tiên của một chuỗi cụ thể, sử dụng phương thức Remove(string). Phương thức trả về true nếu tìm thấy và xóa, ngược lại false.
Ví dụ 1: Xóa "100" từ mảng có phần tử trùng lặp
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "100", "400", "500" };
Console.WriteLine("Các phần tử của mảng...");
foreach (string res in arr)
Console.WriteLine(res);
stringCol.AddRange(arr);
Console.WriteLine("Tổng số phần tử = " + stringCol.Count);
stringCol.Remove("100");
Console.WriteLine("Tổng số phần tử bây giờ = " + stringCol.Count);
}
}
Kết quả
Các phần tử của mảng... 100 200 100 400 500 Tổng số phần tử = 5 Tổng số phần tử bây giờ = 4
Ví dụ 2: Xóa nhiều chuỗi khác nhau
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "10", "20", "30", "40", "50", "60", "70", "80" };
Console.WriteLine("Các phần tử của mảng...");
foreach (string res in arr)
Console.WriteLine(res);
stringCol.AddRange(arr);
Console.WriteLine("Tổng số phần tử = " + stringCol.Count);
stringCol.Remove("50");
stringCol.Remove("60");
stringCol.Remove("70");
Console.WriteLine("Tổng số phần tử bây giờ = " + stringCol.Count);
}
}
Kết quả
Các phần tử của mảng... 10 20 30 40 50 60 70 80 Tổng số phần tử = 8 Tổng số phần tử bây giờ = 5
Lưu ý: StringCollection cho phép phần tử trùng lặp. Remove chỉ xóa lần xuất hiện đầu tiên tìm thấy (theo chỉ số thấp nhất).