【问题标题】:List AddRange from a specific index?从特定索引列出 AddRange?
【发布时间】:2013-12-13 13:35:58
【问题描述】:

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

例如:

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 add


【解决方案1】:

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

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

这是live example

【讨论】:

    【解决方案2】:
    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 方法结合使用,该方法将跳过第一个元素。如果要在特定索引之后插入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多