Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Insert an object in a list at custom index

Tags:

c#

.net

object

list

I have an empty list defined to hold 120 values, I want to insert an element at index(45), even though the list is currently empty. Is this possible?

public List<Ticket> Tickets = new List<Ticket>(120);

Tickets.Insert(45,ticket); // Here I am getting the ArgumentOutOfRangeException
like image 616
Naughty Ninja Avatar asked Dec 23 '15 13:12

Naughty Ninja


2 Answers

You set the initial internal capacity of the list to 120. The list is still empty.

List<T> can hold any number of items. Internally, it uses an array to store them. If the array gets full, the list will allocate a new, larger one. If you know the number of items in advance, you can set the size of the internal array when you construct the list. This way you can avoid unnecessary memory allocation.

You could use an array:

Ticket[] tickets = new Ticket[120];
tickets[45] = ticket

or a Dictionary<int, Ticket>

Dictionary<int, Ticket> tickets = new Dictionary<int, Ticket>();
tickets.Add(45, ticket);

or create a List<Ticket> holding 120 nulls:

List<Ticket> tickets = Enumerable.Repeat(default(Ticket), 120).ToList();
like image 108
Jakub Lortz Avatar answered Oct 05 '22 04:10

Jakub Lortz


120 is defined as the capacity of the list - not the really existing elements. So in this case your list contains 0 elements at insert.

When you try to insert a element at position 45 into a empty list - a ArgumentOutOfRangeException makes sense

like image 26
fubo Avatar answered Oct 05 '22 03:10

fubo