Question Remove an item from an Array

dotnetnube

Member
Joined
Aug 20, 2008
Messages
8
Programming Experience
Beginner
I want to remove an item from an array completely...not just set it to "Nothing". Is this possible?

I have an array of files, that as I delete a file, I would like to remove the deleted file from the array:

Dim sourceDir As DirectoryInfo
Dim sourceFiles as FileInfo()

sourceDir = "\\path\folder\"
sourceFiles = sourceDir.GetFiles(fileName.Item("SourceName").ToString)


I am currently using this line of code to "remove" an item from the array:

array.clear(sourceFiles, item, 1)

The problem (for me) is that all this is doing is setting this sourceFiles item to "Nothing", but it isn't removing it from the array. How do I remove it from the array?

Thank you in advance!
 
I'd suggest using a List(Of FileInfo)

VB.NET:
		Dim sourceDir As New DirectoryInfo("C:\Temp\")
		Dim sourceFiles As New List(Of FileInfo)

		sourceFiles.AddRange(sourceDir.GetFiles("*.txt"))

		Do While sourceFiles.Count > 0
			MessageBox.Show(sourceFiles.Item(0).FullName)
			sourceFiles.RemoveAt(0)
		Loop
 
I want to remove an item from an array completely...not just set it to "Nothing". Is this possible?

I have an array of files, that as I delete a file, I would like to remove the deleted file from the array:

Dim sourceDir As DirectoryInfo
Dim sourceFiles as FileInfo()

sourceDir = "\\path\folder\"
sourceFiles = sourceDir.GetFiles(fileName.Item("SourceName").ToString)


I am currently using this line of code to "remove" an item from the array:

array.clear(sourceFiles, item, 1)

The problem (for me) is that all this is doing is setting this sourceFiles item to "Nothing", but it isn't removing it from the array. How do I remove it from the array?

Thank you in advance!
To completely remove item from an array like that you'd need to create a copy of the current one first, then ReDim the old one then loop through the new one to copy the items from the new to the redimmed old one.

Or you could simply use a List(Of T), in this case of FileInfo.
 
How do I remove it from the array?

The learning point here is that arrays are a fixed size. You declare an array that can hold 6 items, it's like a wine carrier; it is always able to hold 6 items.

If your wine carrier has 4 bottles in, it has 2 empty slots too. Normally you'd not care, and any process you were doing that looped over the array would just check if the current item was Nothing and if so, move on without doing anything.

If you really want your wine carrier to have only 4 slots all filled with bottles, you have to make a new carrier with only 4 slots, transfer the bottles and discard the old 6 bottle carrier. (What Juggalo said: make a new array dimmed to the old one's size, less one, copy the old items into the array using a loop or array.copy, discard the old array)

List(of T) does this internally automatically

Make sense?
 
Back
Top