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

C#List

C# 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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbANView Question on Stackoverflow
Solution 1 - C#leppieView Answer on Stackoverflow
Solution 2 - C#Henk HoltermanView Answer on Stackoverflow
Solution 3 - C#Daniel GehrigerView Answer on Stackoverflow
Solution 4 - C#Martin BuberlView Answer on Stackoverflow
Solution 5 - C#Tedd HansenView Answer on Stackoverflow
Solution 6 - C#wRARView Answer on Stackoverflow
Solution 7 - C#SWekoView Answer on Stackoverflow