kaivalya
kaivalya

Reputation: 4671

Adding object to the beginning of generic List<T>

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?

Upvotes: 51

Views: 46562

Answers (3)

Guffa
Guffa

Reputation: 700332

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.

Upvotes: 4

Martin Brown
Martin Brown

Reputation: 25310

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

Upvotes: 9

Marc Gravell
Marc Gravell

Reputation: 1062780

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>

Upvotes: 91

Related Questions