C#List <T>.InsertRange()方法用于在列表中的指定索引处插入相同类型的元素的集合。
语法:
void List<T>.InsertRange(int index, IEnumerable<T> collection);
参数:它接受两个参数:1)index–插入元素的位置;2)collection–T类型元素的集合。
返回值:不返回任何内容–返回类型为void。
示例
int list declaration:
List<int> a = new List<int>();
adding elements:
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
//在指定索引处插入元素(数组)
int[] arr = { 100, 200, 300 };
a.InsertRange(3, arr);
Output:
10 20 30 100 200 300 40 50using System;
using System.Text;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void printList(List<int> lst)
{
//打印元素
foreach (int item in lst)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//整数列表
List<int> a = new List<int>();
//添加元素
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
//打印列表
Console.WriteLine("列表元素...");
printList(a);
//在指定索引处插入元素(数组)
int[] arr = { 100, 200, 300 };
a.InsertRange(3, arr);
//插入元素后列出
Console.WriteLine("插入元素后列出元素...");
printList(a);
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
列表元素... 10 20 30 40 50 插入元素后列出元素... 10 20 30 100 200 300 40 50
参考:List <T> .InsertRange(Int32,IEnumerable <T>)方法