Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you .Remove() a specific item from a List<T> does it also remove the 'empty slot'?

Tags:

c#

Feel free to correct my terminology, and understanding of the List if needed..

If I have a list of five items where each item has a unique ID...

[item 1]
[item 2]
[item 3]
[item 4]
[item 5]

and I remove item with ID 72 (for example) and it happens to be 3rd in the List...

will it end up like this...

[item 1]
[item 2]
[null]
[item 4]
[item 5]

or like this

[item 1]
[item 2]
[item 3]
[item 4]

where what used to be item 4 is now item 3, etc.

Please explain if you can :)

like image 640
MetaGuru Avatar asked Oct 05 '10 14:10

MetaGuru


People also ask

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.

What happens when you delete element in an array?

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

What does the RemoveAt method of a list object do?

Removes the first occurrence of a specific object from the List<T>.


2 Answers

Second option. It behaves as a List, not as an array.

It is possible to remove an element at a particular index. The indices of previous elements at that and higher indices are decreased by 1.

like image 166
matiash Avatar answered Oct 19 '22 19:10

matiash


Actually, with the implementation of System.Collections.Generic.List<T>, the underlying array that is used to store items will end up like this:

[item 1]
[item 2]
[item 4]
[item 5]
[null]

That is, without changing the size of the array, the 3rd item has been removed and the 4th and 5th items have been shifted.

Of course if you enumerate the collection the trailing nulls are omitted because the size of the collection is used to determine where to stop. (Edit: And attempts to access indicies beyond the logical end of the collection will fail.)

like image 6
Michael Petito Avatar answered Oct 19 '22 19:10

Michael Petito