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

Chèn phần tử vào Collection<T> tại chỉ số chỉ định trong C#

Giới thiệu

Collection<T> (namespace System.Collections.ObjectModel) là base class cho collection tùy chỉnh, hỗ trợ Insert(int index, T item). Khác với List, nó cung cấp các phương thức virtual InsertItem, SetItem... để override hành vi.

Ví dụ 1: Insert cơ bản

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection col = new Collection();
        col.Add("Laptop");
        col.Add("Desktop");
        col.Add("Notebook");
        col.Add("Ultrabook");
        col.Add("Tablet");
        col.Add("Headphone");
        col.Add("Speaker");

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

        Console.WriteLine($"\nPhần tử index 3: {col[3]}"); // Ultrabook
        Console.WriteLine($"Phần tử index 4: {col[4]}"); // Tablet

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

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

Kết quả

Ban đầu:
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker

Phần tử index 3: Ultrabook
Phần tử index 4: Tablet

Sau Insert(5, 'Alienware'):
Laptop
Desktop
Notebook
Ultrabook
Tablet
Alienware
Headphone
Speaker

Ví dụ 2: Insert với trùng lặp

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection col = new Collection();
        col.Add("Andy"); col.Add("Kevin"); col.Add("John");
        col.Add("Kevin"); col.Add("Mary"); col.Add("Katie");
        col.Add("Barry"); col.Add("Nathan");

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

        col.Insert(3, "Jacob"); // Chèn tại index 3 (trước Kevin thứ 2)

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

Kết quả

Ban đầu:
Andy
Kevin
John
Kevin
Mary
Katie
Barry
Nathan

Sau Insert(3, 'Jacob'):
Andy
Kevin
John
Jacob
Kevin
Mary
Katie
Barry
Nathan

Tạo Custom Collection (Override InsertItem)

using System;
using System.Collections.ObjectModel;

public class NotNullCollection : Collection where T : class
{
    protected override void InsertItem(int index, T item)
    {
        if (item == null) throw new ArgumentNullException(nameof(item));
        base.InsertItem(index, item);
    }
}

public class Demo
{
    public static void Main()
    {
        var col = new NotNullCollection();
        col.Add("A");
        col.Insert(0, "B"); // OK
        // col.Insert(1, null); // Throw ArgumentNullException
    }
}

Lưu ý

  • index hợp lệ: 0 <= index <= Count.
  • Phức tạp: O(n) do phải dịch chuyển phần tử (dùng mảng nội bộ).
  • Collection<T> phù hợp làm base class cho public API, cho phép kiểm soát thêm/xóa/sửa.
  • Cho code nội bộ, dùng List<T> nhanh hơn.