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?
To do what you want, you have two options. You can use List<object>, and handle objects. This will not be typesafe, and will have boxing/unboxing issues for value types, but it will work. Your other option is to use a generic constraint to limit to a base class or interface, and use a List<Interface>.
Add() method adds an object to the end of the List<T>. List. AddRange() method adds a collection of objects to the end of the List<T>. The following code example adds three int objects to the end of the List<int> using Add method.
Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With