One answer is to create a new array that is one element shorter. Are there any other simpler ways to do this?
You can use LINQ to produce your result in a very concise bit of code:
Dim a2 = a.Skip(1).ToArray();
You may have detractors say that this is slow and that you should use Array.Copy
instead:
Dim a2(a.Length - 2) as Integer
Array.Copy(a, 1, a2, 0, a.Length - 1)
However, I tested the timings of both methods using an array of integers with 1,000,000 elements and found that LINQ took 29 milliseconds and the direct copy took 3 milliseconds. Unless you're doing some sort of crazy math with gazilions of elements then LINQ is fine and is far more readable.
Here is one way to remove the first element of an array in vb.net.
dim a(n)
...
for i = 1 to ubound(a)
a(i-1) = a(i)
next i
redim preserve a(ubound(a)-1)
You could make a function for this to remove an arbitrary element of an array (Have a parameter for the initial value of the for loop).
Combining @xpda's and @Enigmativity's answers, observe that Array.Copy can be safely used to copy back to the original array. Quote from msdn page for Array.Copy Method:
If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.
Here is an (extension) subroutine that will remove element, at specified index, of an array of any type:
' Remove element at index "index". Result is one element shorter.
' Similar to List.RemoveAt, but for arrays.
<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef a() As T, ByVal index As Integer)
' Move elements after "index" down 1 position.
Array.Copy(a, index + 1, a, index, UBound(a) - index)
' Shorten by 1 element.
ReDim Preserve a(UBound(a) - 1)
End Sub
Usage examples (assuming array starting with index 0):
a.RemoveAt(0) ' Remove first element
a.RemoveAt(1) ' Remove second element.
a.RemoveAt(UBound(a)) ' Remove last element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With