在 C# 列表中一次性插入多個元素


使用 InsertRange() 方法可向 C# 中現有列表中插入列表。透過此種方法,你可以輕鬆地向現有列表中新增一個以上的元素。

首先,讓我們設定一個列表 -

List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);

現在,讓我們設定一個數組。此陣列的元素將被新增到上述列表中 -

int[] arr2 = new int[4];
arr2[0] = 60;
arr2[1] = 70;
arr2[2] = 80;
arr2[3] = 90;

我們將上述元素新增到列表中 -

arr1.InsertRange(5, arr2);

這是完整程式碼 -

示例

 即時預覽

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> arr1 = new List<int>();
      arr1.Add(10);
      arr1.Add(20);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      Console.WriteLine("Initial List ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
      int[] arr2 = new int[4];
      arr2[0] = 60;
      arr2[1] = 70;
      arr2[2] = 80;
      arr2[3] = 90;
      arr1.InsertRange(5, arr2);
      Console.WriteLine("After adding elements ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
   }
}

輸出

Initial List ...
10
20
30
40
50
After adding elements ...
10
20
30
40
50
60
70
80
90

更新日期: 22-Jun-2020

超過 3K 次瀏覽

開啟您的 職業生涯

透過完成該課程獲得認證

立即開始
廣告