通用列表中是否有内置函数可以从特定索引中添加另一个列表中的范围,还是我必须编写自己的函数?
例如:
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。
我应该自己编写还是有内置函数可以做到这一点?
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 方法结合使用,这将跳过第一个元素。如果您想在特定索引之后插入。
有
List<T>.InsertRange(Int32, IEnumerable<T>) Method
将集合的元素插入到 List 的指定索引处。其中 Int32
是应插入新元素的从零开始的索引,IEnumerable<T>
是应将其元素插入 List 的集合。 .
在你的例子中:
list2.InsertRage(1, list1)