C# 列表中的 AddRange 方法是什麼?


列表中的 AddRange 方法新增一個完整的元素集合。我們來看一個例子 −

首先,設定一個 C# 列表並新增元素 −

List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);

現在設定一個要新增到列表的元素陣列 −

// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;

使用 AddRange() 方法將整個元素集合新增到列表 −

list.AddRange(arr);

現在讓我們看看完整的程式碼並顯示列表 −

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      List<int> list = new List<int>();
      list.Add(100);
      list.Add(200);
      list.Add(300);
      list.Add(400);

      // array of 4 elements
      int[] arr = new int[4];
      arr[0] = 500;
      arr[1] = 600;
      arr[2] = 700;
      arr[3] = 800;
   
      list.AddRange(arr);

      foreach (int val in list) {
         Console.WriteLine(val);
      }
   }
}

更新於: 2020 年 6 月 20 日

6K+ 瀏覽量

Kickstart Your Career

完成課程透過認證

開始
廣告
© . All rights reserved.