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

13,273

Solution 1

Use InsertRange method:

 myList.InsertRange(0, moreItems);

Solution 2

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);

Solution 3

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.

Solution 4

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

Share:
13,273

Related videos on Youtube

Dave New
Author by

Dave New

Updated on September 25, 2022

Comments

  • Dave New
    Dave New over 1 year

    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
      Dave New
      Sorry, I never thought to look at Insert...
  • Martijn Pieters
    Martijn Pieters over 11 years
    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.