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?
An array of strings is created and passed to the constructor, populating the list with the elements of the array. The AddRange method is called, with the list as its argument. The result is that the current elements of the list are added to the end of the list, duplicating all the elements.
Press F5 or CTRL+G to launch the Go To dialog. In the Go to list, click the name of the cell or range that you want to select, or type the cell reference in the Reference box, then press OK.
List<T>. AddRange(IEnumerable<T>) Method is used to add the elements of the specified collection to the end of the List<T>.
Not in-built to AddRange, but you could use LINQ:
list2.Add(100);
list2.AddRange(list1.Skip(1));
Here is a live 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.InsertRange(1,list1.Skip(1));
Output on Printing:
100
20
30
You can use InsertRange combined with a linq skip method, which will skip the first element. If you want to insert after a specific index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With