Giới thiệu
StringCollection (namespace System.Collections.Specialized) là một tập hợp chuyên biệt chỉ chứa các chuỗi. Phương thức Clear() xóa tất cả phần tử khỏi tập hợp.
Ví dụ 1: Xóa tất cả phần tử từ mảng số
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("Array elements...");
foreach (string res in arr)
{
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Does the specified string is in the StringCollection? = " + stringCol.Contains("800"));
Console.WriteLine("Total number of elements = " + stringCol.Count);
stringCol.Clear();
Console.WriteLine("\nWe have removed all the elements now..");
Console.WriteLine("Total number of elements now = " + stringCol.Count);
}
}
Kết quả
Array elements... 100 200 300 400 500 Does the specified string is in the StringCollection? = False Total number of elements = 5 We have removed all the elements now.. Total number of elements now = 0
Ví dụ 2: Xóa tất cả phần tử từ mảng chữ cái
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
Console.WriteLine("Array elements...");
foreach (string res in arr)
{
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Count of elements = " + stringCol.Count);
stringCol.Clear();
Console.WriteLine("\nRemoved all the elements now...");
Console.WriteLine("Total number of elements now = " + stringCol.Count);
}
}
Kết quả
Array elements... A B C D E F G H I J Count of elements = 10 Removed all the elements now... Total number of elements now = 0
Các phương thức hữu ích khác của StringCollection
Add(string)- Thêm một chuỗiAddRange(string[])- Thêm nhiều chuỗi từ mảngRemove(string)- Xóa một chuỗi cụ thểContains(string)- Kiểm tra sự tồn tạiIndexOf(string)- Tìm chỉ mục của chuỗiInsert(int, string)- Chèn chuỗi tại vị trí cụ thể