hello,
how can i delete a item from an array (vb.net)?
thanks
hello,
how can i delete a item from an array (vb.net)?
thanks
Hi there.
You can't. I would suggest that you put the array elements into a List
, at least then you can remove items. An array can be extended, for example using ReDim
but you cannot remove array elements once they have been created. You would have to rebuild the array from scratch to do that.
If you can avoid it, don't use arrays here, use a List
.
Cheers. Jas.
That depends on what you mean by delete. An array has a fixed size, so deleting doesn't really make sense.
If you want to remove element i
, one option would be to move all elements j > i
one position to the left (a[j - 1] = a[j]
for all j
, or using Array.Copy
) and then resize the array using ReDim Preserve.
So, unless you are forced to use an array by some external constraint, consider using a data structure more suitable for adding and removing items. List<T>, for example, also uses an array internally but takes care of all the resizing issues itself: For removing items, it uses the algorithm mentioned above (without the ReDim), which is why List<T>.RemoveAt
is an O(n) operation.
There's a whole lot of different collection classes in the System.Collections.Generic namespace, optimized for different use cases. If removing items frequently is a requirement, there are lots of better options than an array (or even List<T>
).
As Heinzi said, an array has a fixed size. In order to 'remove an item' or 'resize' it, you'll have to create a new array with the desired size and copy the items you need as appropriate.
Here's code to remove an item from an array:
<System.Runtime.CompilerServices.Extension()> _
Function RemoveAt(Of T)(ByVal arr As T(), ByVal index As Integer) As T()
Dim uBound = arr.GetUpperBound(0)
Dim lBound = arr.GetLowerBound(0)
Dim arrLen = uBound - lBound
If index < lBound OrElse index > uBound Then
Throw New ArgumentOutOfRangeException( _
String.Format("Index must be from {0} to {1}.", lBound, uBound))
Else
'create an array 1 element less than the input array
Dim outArr(arrLen - 1) As T
'copy the first part of the input array
Array.Copy(arr, 0, outArr, 0, index)
'then copy the second part of the input array
Array.Copy(arr, index + 1, outArr, index, uBound - index)
Return outArr
End If
End Function
You can use it as such:
Module Module1
Sub Main()
Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1)
End Sub
End Module
The code above removes the second element ("mno"
) [which has an index of 1] from the array.
You need to be developing in .NET 3.5 or higher in order to use the extension method. If you're using .NET 2.0 or 3.0, you can call the method as such
arr = RemoveAt(arr, 1)
I hope this is what you need.