在 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 次浏览

开启您的 职业生涯

通过完成该课程获得认证

立即开始
广告