Adding object to the beginning of generic List<T>

Viewed 40858

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?

3 Answers

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>

List<T> l = new List<T>();
l.Insert(0, item);

You can insert items at the beginning of the list, but that is not very efficient, especially if there are many items in the list.

To avoid that you can 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.

Related