C#List <T>.Insert()方法用于在列表中的指定索引处插入元素。
语法:
void List<T>.Insert(int index, T item);
参数:它接受两个参数:1)索引–您要在其中插入元素的位置;和2)项目–要在列表中插入的参数。
返回值:不返回任何内容–返回类型为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); //在指定索引处插入元素 a.Insert(1, 100); a.Insert(3, 200); a.Insert(4, 300); Output: 10 100 20 200 300 30 40 50
using 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("list elements...");
printList(a);
//在指定索引处插入元素
a.Insert(1, 100);
a.Insert(3, 200);
a.Insert(4, 300);
//插入元素后列出
Console.WriteLine("list elements after inserting elements...");
printList(a);
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
list elements... 10 20 30 40 50 list elements after inserting elements... 10 100 20 200 300 30 40 50
参考:List <T> .Insert(Int32,T)方法