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

Chèn chuỗi vào StringCollection tại chỉ số chỉ định trong C#

Giới thiệu

StringCollection (namespace System.Collections.Specialized) là danh sách chuỗi **không generic**, cho phép trùng lặp. Phương thức Insert(int index, string value) chèn chuỗi tại vị trí index, dịch các phần tử sau sang phải.

Ví dụ 1: Chèn một phần tử

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection col = new StringCollection();
        col.Add("Accessories");
        col.Add("Books");
        col.Add("Electronics");

        Console.WriteLine("Ban đầu:");
        foreach (string s in col) Console.WriteLine(s);

        col.Insert(2, "Headphone"); // Chèn trước "Electronics"

        Console.WriteLine("\nSau Insert(2, 'Headphone'):");
        foreach (string s in col) Console.WriteLine(s);
    }
}

Kết quả

Ban đầu:
Accessories
Books
Electronics

Sau Insert(2, 'Headphone'):
Accessories
Books
Headphone
Electronics

Ví dụ 2: Chèn nhiều lần liên tiếp

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection col = new StringCollection();
        col.Add("Laptop");
        col.Add("Desktop");
        col.Add("Tablet");
        col.Add("Speakers");

        Console.WriteLine("Ban đầu:");
        foreach (string s in col) Console.WriteLine(s);

        col.Insert(2, "Headphone");
        col.Insert(3, "Alienware");

        Console.WriteLine("\nSau 2 lần Insert:");
        foreach (string s in col) Console.WriteLine(s);

        col.Insert(4, "E-Book Reader");
        col.Insert(5, "Monitor");
        col.Insert(6, "HDD");
        col.Insert(7, "SSD");

        Console.WriteLine("\nSau thêm 4 lần nữa:");
        foreach (string s in col) Console.WriteLine(s);
    }
}

Kết quả

Ban đầu:
Laptop
Desktop
Tablet
Speakers

Sau 2 lần Insert:
Laptop
Desktop
Headphone
Alienware
Tablet
Speakers

Sau thêm 4 lần nữa:
Laptop
Desktop
Headphone
Alienware
E-Book Reader
Monitor
HDD
SSD
Tablet
Speakers

Đặc điểm StringCollection

  • Chỉ chứa string (non-generic nhưng type-safe cho string).
  • Cho phép **trùng lặp** và null.
  • Hỗ trợ indexer col[index] (đọc/ghi).
  • Phương thức: Add, AddRange, Insert, Remove, RemoveAt, Clear, Contains, IndexOf, CopyTo.
  • Implement IList, ICollection, IEnumerable.

So sánh với List<string>

Đặc điểmStringCollectionList<string>
GenericKhôngCó
Hiệu năngThấp hơn (boxing interface)Cao
Thread-safeKhôngKhông
Khuyến nghịLegacy onlyMặc định cho code mới

Lưu ý

  • Insert ném ArgumentOutOfRangeException nếu index < 0 hoặc > Count.
  • Dùng List<string> cho code mới: list.Insert(index, value) cùng cú pháp.