从特定索引列出 AddRange?

问题描述 投票:0回答:3

通用列表中是否有内置函数可以从特定索引中添加另一个列表中的范围,还是我必须编写自己的函数?

例如:

List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

list1.Add(10);
list1.Add(20);
list1.Add(30);

list2.Add(100);
//list2.AddRange(list1, 1) Add from list1 from the index 1 till the end

在此示例中,list2 应具有 3 个元素:100、20 和 30。

我应该自己编写还是有内置函数可以做到这一点?

c# list addition
3个回答
10
投票

不是内置于 AddRange,但您可以使用 LINQ:

list2.Add(100);
list2.AddRange(list1.Skip(1));

这是一个实例


5
投票
List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

list1.Add(10);
list1.Add(20);
list1.Add(30);

list2.Add(100);
list2.InsertRange(1,list1.Skip(1));

打印输出:

100

20

30

您可以将 InsertRange 与 linq Skip 方法结合使用,这将跳过第一个元素。如果您想在特定索引之后插入。


0
投票

List<T>.InsertRange(Int32, IEnumerable<T>) Method
将集合的元素插入到 List 的指定索引处。其中
Int32
是应插入新元素的从零开始的索引,
IEnumerable<T>
是应将其元素插入 List 的集合。 .

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insertrange?view=net-7.0

在你的例子中:

list2.InsertRage(1, list1)
© www.soinside.com 2019 - 2024. All rights reserved.