186

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!

bAN
  • 12,613
  • 15
  • 58
  • 92

7 Answers7

398
List<T>.Insert(0, item);
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
leppie
  • 112,162
  • 17
  • 191
  • 293
82
 myList.Insert(0, item);

         

Henk Holterman
  • 250,905
  • 30
  • 306
  • 490
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
16

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

Martin Buberl
  • 43,672
  • 25
  • 98
  • 142
11

You do that by inserting into position 0:

List myList = new List();
myList.Insert(0, "test");
Tedd Hansen
  • 11,595
  • 14
  • 59
  • 96
10

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

wRAR
  • 24,218
  • 4
  • 82
  • 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