tags:

views:

175

answers:

3

Add method Adds an object to the end of the List<T>

What would be a quick and efficient way of adding object to the beginning of a list

+16  A: 

Well, list.Insert(0, obj) - but that has to move everything. If you need to be able to insert at the start efficiently, consider a Stack<T> or a LinkedList<T>

Marc Gravell
Or just pretend the beginning is the end (invert all your indexes so i = list.Length - i and iterate from back to front)
Joel Coehoorn
True - that would be good to remove the Stack<T> case - but if you need more versatility, LinkedList<T> may have a part to play.
Marc Gravell
Stack would be fine..
Syed Tayyab Ali
+1  A: 
List<T> l = new List<T>();
l.Insert(0, item);
Martin Brown
+1  A: 

Redefine what you use as beginning and end of the list, so that the last element is the beginning of the list. Then you just use Add to put an element at the beginning of the list, which is much more efficient than inserting items at position zero.

Guffa