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

Tạo StringCollection trong C#

Giới thiệu

StringCollection (namespace System.Collections.Specialized) là collection chuyên biệt chỉ chứa string, non-generic, cho phép trùng lặp và null. Implement IList, ICollection, IEnumerable.

Ví dụ 1: Tạo từ mảng string, AddRange, truy xuất index

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection col = new StringCollection();
        string[] arr = { "A", "B", "C", "D", "E", "F", "G", "H" };

        Console.WriteLine("Mảng ban đầu:");
        foreach (string s in arr) Console.WriteLine(s);

        col.AddRange(arr);

        Console.WriteLine($"\nPhần tử index 5: {col[5]}"); // F
        Console.WriteLine($"Count: {col.Count}"); // 8
    }
}

Kết quả

Mảng ban đầu:
A
B
C
D
E
F
G
H

Phần tử index 5: F
Count: 8

Ví dụ 2: AddRange từ mảng có trùng, Remove

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection col = new StringCollection();
        string[] arr = { "100", "200", "100", "400", "500" };

        Console.WriteLine("Mảng:");
        foreach (string s in arr) Console.WriteLine(s);

        col.AddRange(arr);
        Console.WriteLine($"\nCount sau AddRange: {col.Count}"); // 5

        col.Remove("100"); // Xóa **phần tử đầu tiên** khớp
        Console.WriteLine($"Count sau Remove('100'): {col.Count}"); // 4

        Console.WriteLine("\nCác phần tử còn lại:");
        foreach (string s in col) Console.WriteLine(s);
    }
}

Kết quả

Mảng:
100
200
100
400
500

Count sau AddRange: 5
Count sau Remove('100'): 4

Các phần tử còn lại:
200
100
400
500

Các phương thức chính

Phương thứcMô tả
Add(string)Thêm 1 chuỗi
AddRange(string[])Thêm mảng chuỗi
Insert(index, string)Chèn tại vị trí
Remove(string)Xóa lần đầu tìm thấy
RemoveAt(index)Xóa tại index
Clear()Xóa tất cả
Contains(string)Kiểm tra tồn tại
IndexOf(string)Tìm index đầu tiên
CopyTo(string[], index)Copy sang mảng

So sánh với List<string>

Đặc điểmStringCollectionList<string>
GenericKhôngCó
Hiệu năngThấp (boxing interface)Cao
Type-safeCó (chỉ string)Có
LINQ supportCần Cast<string>()Native
Khuyến nghịLegacy onlyMặc định

Chuyển đổi sang List<string>

StringCollection sc = new StringCollection();
sc.AddRange(new[] { "a", "b", "c" });

List list = new List(sc.Count);
foreach (string s in sc) list.Add(s);
// Hoặc .NET 3.5+:
List list2 = sc.Cast().ToList();