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

Chèn tập hợp phần tử vào List tại chỉ số chỉ định trong C#

Mục đích

Phương thức List<T>.InsertRange(int index, IEnumerable<T> collection) chèn **nhiều phần tử** từ collection vào List tại vị trí index. Các phần tử cũ từ index trở đi dịch sang phải.

Ví dụ 1: Chèn mảng string vào List

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        string[] arr = { "John", "Tom", "Kevin", "Mark", "Gary" };
        List list = new List(arr);

        Console.WriteLine("List ban đầu:");
        foreach (string s in list) Console.WriteLine(s);

        string[] newItems = { "Demo", "Text" };
        list.InsertRange(3, newItems); // Chèn tại index 3 (trước "Mark")

        Console.WriteLine("\nSau InsertRange(3, newItems):");
        foreach (string s in list) Console.WriteLine(s);
    }
}

Kết quả

List ban đầu:
John
Tom
Kevin
Mark
Gary

Sau InsertRange(3, newItems):
John
Tom
Kevin
Demo
Text
Mark
Gary

Ví dụ 2: Chèn mảng int

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        int[] arr = { 10, 20, 30, 40, 50 };
        List list = new List(arr);

        Console.WriteLine("List ban đầu:");
        foreach (int i in list) Console.WriteLine(i);

        int[] more = { 300, 400, 500 };
        list.InsertRange(2, more); // Chèn tại index 2 (trước 30)

        Console.WriteLine("\nSau InsertRange(2, more):");
        foreach (int i in list) Console.WriteLine(i);
    }
}

Kết quả

List ban đầu:
10
20
30
40
50

Sau InsertRange(2, more):
10
20
300
400
500
30
40
50

Đặc điểm

  • index hợp lệ: 0 <= index <= Count. index == Count = AddRange.
  • Tham số collection là bất kỳ IEnumerable<T> (array, List, HashSet, yield iterator...).
  • Phức tạp: O(n + m) với n = Count - index (phần tử dịch), m = collection.Count.
  • Ném ArgumentNullException nếu collection null. ArgumentOutOfRangeException nếu index sai.

So sánh Insert vs InsertRange

// Insert 1 phần tử
list.Insert(2, 999);

// Insert nhiều phần tử (hiệu quả hơn nhiều lần Insert)
list.InsertRange(2, new[] { 999, 888, 777 });

Ví dụ nâng cao: Chèn kết quả LINQ


List list = new List { 1, 2, 3, 4, 5 };
// Chèn các số chẵn từ 10-20 tại index 2
list.InsertRange(2, Enumerable.Range(10, 11).Where(x => x % 2 == 0));
// Kết quả: 1, 2, 10, 12, 14, 16, 18, 20, 3, 4, 5