在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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短