Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 204
Dave New Avatar asked Dec 05 '12 10:12

Dave New


People also ask

How do you add a range to a list?

Use the list. extend() method to append a range to a list in Python, e.g. my_list. extend(range(2)) . The extend method takes an iterable (such as a range) and extends the list by appending all of the items from the iterable.

How do I add an item to the beginning of a list in Python?

Use the + Operator to Append an Element to the Front of a List in Python. Another approach to append an element to the front of a list is to use the + operator. Using the + operator on two or more lists combines them in the specified order.

How do you add an element at the beginning of the list?

insert(index, value)this inserts an item at a given position. The first argument is the index of the element before which you are going to insert your element, so array. insert(0, x) inserts at the front of the list, and array. insert(len(array), x) is equivalent to array.


2 Answers

Use InsertRange method:

 myList.InsertRange(0, moreItems); 
like image 159
Sergey Berezovskiy Avatar answered Oct 19 '22 07:10

Sergey Berezovskiy


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); 
like image 30
Soner Gönül Avatar answered Oct 19 '22 07:10

Soner Gönül