Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List AddRange from a specific index?

Tags:

c#

list

add

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?

like image 449
Assassinbeast Avatar asked Dec 13 '13 13:12

Assassinbeast


People also ask

What is AddRange in list C#?

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.

How do you select a range in a list?

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.

What is AddRange in Linq?

List<T>. AddRange(IEnumerable<T>) Method is used to add the elements of the specified collection to the end of the List<T>.


2 Answers

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

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

Here is a live example.

like image 169
CodingIntrigue Avatar answered Sep 20 '22 10:09

CodingIntrigue


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.

like image 41
Kishore Kumar Avatar answered Sep 21 '22 10:09

Kishore Kumar