Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding object to the beginning of generic List<T>

Tags:

c#

.net

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?

like image 722
kaivalya Avatar asked Apr 01 '09 15:04

kaivalya


People also ask

How do you add an object to a generic 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>.

How do you add an object to a list in C sharp?

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.

Why does adding a new value to list <> overwrite previous values in the list <>?

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!


2 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>

like image 189
Marc Gravell Avatar answered Oct 13 '22 05:10

Marc Gravell


List<T> l = new List<T>(); l.Insert(0, item); 
like image 23
Martin Brown Avatar answered Oct 13 '22 06:10

Martin Brown