windowsgm
windowsgm

Reputation: 1616

Adding to List at Specific Index

Do I have to use an Array if I want to add items at a specified index before having items before that index or is it possible to use a List? Or would I have to fill the list in with dummy data first just so I can add in at the exact index I want?

I.e. I create a List< int>(10) and want to add an int at the index of 5 before having anything in 0-4.

Upvotes: 2

Views: 2096

Answers (1)

ChrisF
ChrisF

Reputation: 137148

You have to have an array.

An array can contain empty elements, whereas a list cannot. Though in your case of integers you would need to use a special value (0, -1, -MaxInt, whatever) to indicate an empty element.

Once you have a list you can, however, insert elements into the list at any location though that will push all other elements "along" the list.

I have just thought, however, that you could add "null" elements to the list, but then you would have to replace elements rather than inserting new ones.

Upvotes: 2

Related Questions