I just have a List<T>
and I would like to add an item to this list but at the first position.
MyList.add()
adds the item as the last. How can I add it as the first?.
Thanks for help!
myList.Insert(0, item);
This does involve shifting all the contents of the List internally so if you do this a lot (ie only add to the front) you might consider using a Stack<T>
or a regular List that you read backwards or reverse at some opportune moment.
I would stay away from LinkedList (as long as i could).
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.
You do that by inserting into position 0:
List myList = new List();
myList.Insert(0, "test");
Of course, Insert
or AddFirst
(for a LinkedList) will do the trick, but you could always do:
myList.Reverse();
myList.Add(item);
myList.Reverse();
Note that while this will get you there eventually, it sure is not the most effective way to go ;).