Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xóa tất cả chuỗi khỏi StringCollection trong C#

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ỗi
  • AddRange(string[]) - Thêm nhiều chuỗi từ mảng
  • Remove(string) - Xóa một chuỗi cụ thể
  • Contains(string) - Kiểm tra sự tồn tại
  • IndexOf(string) - Tìm chỉ mục của chuỗi
  • Insert(int, string) - Chèn chuỗi tại vị trí cụ thể