Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add to a List's first position? [duplicate]

Tags:

c#

list

People also ask

How to add value to existing list in c#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);

How do you append to index 0 in Python?

Solution: Use the list. insert(0, x) element to insert the element x at the first position 0 in the list. All elements j>0 will be moved by one index position to the right.

Can we create a list inside another list?

The items in the outer list are List<int> objects. In the first line, you create the outer list. In the second line, you create a list of int and add it as one of the items in the outer list. In the third line, you add an integer to the first inner list in the outer list.


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

 myList.Insert(0, item);

         


Use List.Insert(0, ...). But are you sure a LinkedList isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one.


Use List<T>.Insert(0, item) or a LinkedList<T>.AddFirst().


You do that by inserting into position 0:

List myList = new List();
myList.Insert(0, "test");

Use Insert method: list.Insert(0, item);