How can I add to a List's first position?
C#ListC# Problem Overview
I just have a List<> and I would like to add an item to this list but at the first position. List.add() add the item at the last.. How can I do that?.. Thanks for help!
C# Solutions
Solution 1 - C#
List<T>.Insert(0, item);
Solution 2 - C#
myList.Insert(0, item);
Solution 3 - C#
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.
Solution 4 - C#
Use List<T>.Insert(0, item)
or a LinkedList<T>.AddFirst()
.
Solution 5 - C#
You do that by inserting into position 0:
List myList = new List();
myList.Insert(0, "test");
Solution 6 - C#
Use Insert
method:
list.Insert(0, item);
Solution 7 - C#
Of course, Insert
or AddFirst
will do the trick, but you could always do:
myList.Reverse();
myList.Add(item);
myList.Reverse();