209

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!

Tolbxela
  • 4,767
  • 3
  • 21
  • 42
bAN
  • 13,375
  • 16
  • 60
  • 93

7 Answers7

435
List<T>.Insert(0, item);
leppie
  • 115,091
  • 17
  • 196
  • 297
95
 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).

H H
  • 263,252
  • 30
  • 330
  • 514
30

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,339
  • 2
  • 34
  • 55
19

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

Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
12

You do that by inserting into position 0:

List myList = new List();
myList.Insert(0, "test");
Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97
11

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

wRAR
  • 25,009
  • 4
  • 84
  • 97
10

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 ;).

Felix
  • 1,066
  • 1
  • 5
  • 22
SWeko
  • 30,434
  • 10
  • 71
  • 106