Vb.net remove first element from array

One answer is to create a new array, which is one of the elements shorter. Are there other simpler ways to do this?

+4
source share
5 answers

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 can make a function for this to remove an arbitrary element of the array (have a parameter for the initial value of the for loop).

+5
source

You can use LINQ to get the result in a very compressed part of the code:

 Dim a2 = a.Skip(1).ToArray(); 

Perhaps your ill-wishers say this is slow and you should use Array.Copy :

 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 takes 29 milliseconds and a direct copy takes 3 milliseconds. If you are not doing some crazy math with gazilia elements, then LINQ is excellent and reads much better.

+12
source

And don't forget - now that you are using .Net, you are no longer strictly limited to using "arrays". You can (and perhaps should, if necessary) use lists, maps, queues, and all kinds of other data structures:

+4
source

Combining the answers of @xpda and @Enigmativity, note that Array.Copy can be safely used to copy back to the original array. Quote from the msdn page for the Array.Copy method:

If sourceArray and destinationArray overlap, this method behaves as if the original sourceArray values ​​were stored in a temporary location before the destinationArray file was overwritten.

Here is a routine (extension) that will remove an element at the 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 the array starts at index 0):

 a.RemoveAt(0) ' Remove first element a.RemoveAt(1) ' Remove second element. a.RemoveAt(UBound(a)) ' Remove last element 
+3
source
 Public xArray as variant Function Array_DeleteFirstItem() Dim i As Integer For i = 0 To UBound(xArray) - 1 xArray (LBound(xArray) + i) = xArray(LBound(NotContainsArray) + i + 1) Next ReDim Preserve xArray(UBound(NotContainsArray) - 1) For i = 0 To UBound(xArray) Debug.Print xArray(i) Next End Function 
0
source

All Articles