Reputation: 4671
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
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
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