C# 在list的指定位置添加元素

使用Insert方法;

代码示例如下:

List<int> temp = new List<int>();
temp.Add(2);
temp.Add(3);
temp.Add(4);
temp.Insert(0,5);

temp结果为5,2,3,4

C#中,可以使用多种方法来给`List`批量添加元素。以下是几种常见的方法: 1. **使用`AddRange`方法**: `AddRange`方法可以将一个集合中的所有元素添加到`List`中。 ```csharp using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); int[] array = { 1, 2, 3, 4, 5 }; list.AddRange(array); Console.WriteLine("List elements: " + string.Join(", ", list)); } } ``` 2. **使用`InsertRange`方法**: `InsertRange`方法可以在指定索引位置插入一个集合中的所有元素。 ```csharp using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int> { 1, 2, 3 }; int[] array = { 4, 5, 6 }; list.InsertRange(1, array); Console.WriteLine("List elements: " + string.Join(", ", list)); } } ``` 3. **使用`foreach`循环**: 可以使用`foreach`循环逐个添加元素。 ```csharp using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); int[] array = { 1, 2, 3, 4, 5 }; foreach (int item in array) { list.Add(item); } Console.WriteLine("List elements: " + string.Join(", ", list)); } } ``` 4. **使用LINQ的`Concat`方法**: 可以使用LINQ的`Concat`方法将两个集合连接起来。 ```csharp using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> list = new List<int> { 1, 2, 3 }; int[] array = { 4, 5, 6 }; list = list.Concat(array).ToList(); Console.WriteLine("List elements: " + string.Join(", ", list)); } } ``` 这些方法都可以有效地批量添加元素到`List`中,具体选择哪种方法可以根据实际需求和代码风格来决定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值