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!
Asked
Active
Viewed 2.1e+01k times
7 Answers
29
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.
Daniel Gehriger
- 7,206
- 2
- 32
- 55
11
You do that by inserting into position 0:
List myList = new List();
myList.Insert(0, "test");
Tedd Hansen
- 11,595
- 14
- 59
- 96
9
Of course, Insert or AddFirst will do the trick, but you could always do:
myList.Reverse();
myList.Add(item);
myList.Reverse();
SWeko
- 29,624
- 9
- 71
- 103
-
6List
doesn't have a AddFirst. – Martin Buberl Jan 20 '11 at 10:43 -
16Let me clarify - this is not a serious response, just a lame effort at a geek joke. – SWeko Jan 20 '11 at 10:45
-
@Reinhard - again, this is not a serious response, just a lame effort at a geek joke – SWeko May 30 '18 at 13:28
-
@Reinhard Perhaps not, because the list is remade in both cases. – RamenTurismo Jun 29 '18 at 08:15