Search code examples
c#listaddition

List AddRange from a specific index?


Is there an inbuilt function in the generic List to add a range from another list in a from a specific index or do I have to write my own?.

For example:

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

In this example, the list2 should have 3 elements: 100, 20 and 30.

Should I write my own or is there an inbuilt function that can do this?


Solution

  • Not in-built to AddRange, but you could use LINQ:

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

    Here is a live example.