28

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?

Dave New
  • 38,496
  • 59
  • 215
  • 394

4 Answers4

52

Use InsertRange method:

 myList.InsertRange(0, moreItems);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4

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);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
2
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.

  • Rather than only post a block of code, please *explain* why this code solves the problem posed. Without an explanation, this is not an answer. – Martijn Pieters Dec 05 '12 at 11:24
1

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

petro.sidlovskyy
  • 5,075
  • 1
  • 25
  • 29