Dave New
Dave New

Reputation: 40022

Add a range of items to the beginning of a list?

The method List<T>.AddRange(IEnumerable<T>) adds a collection of items to the end of the list:

myList.AddRange(moreItems); // Adds moreItems to the end of myList

What is the best way to add a collection of items (as some IEnumerable<T>) to the beginning of the list?

Upvotes: 29

Views: 19606

Answers (4)

List<String> listA=new List<String>{"A","B","C"};
List<String> listB=new List<String>{"p","Q","R"};

listA.InsertRange(0, listB);    

Here suppose we have 2 list of string... then using the InsertRange method we can pass the starting index where we want to insert/push the new range(listB) to the existing range(listA)

Hope this clears the code.

Upvotes: 2

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

Use InsertRange method:

 List<T>.InsertRange(0, yourcollection);

Also look at Insert method which you can add an element in your list with specific index.

Inserts an element into the List at the specified index.

List<T>.Insert(0, T);

Upvotes: 4

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5093

Please try List<T>.InsertRange(0, IEnumerable<T>)

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Use InsertRange method:

 myList.InsertRange(0, moreItems);

Upvotes: 54

Related Questions