How can I delete an item from an array in VB.NET?

前端 未结 11 1722
别那么骄傲
别那么骄傲 2020-12-05 18:14

How can I delete an item from an array in VB.NET?

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 18:33

    Yes, you can delete an element from an array. Here is an extension method that moves the elements as needed, then resizes the array one shorter:

    ' Remove element at index "index". Result is one element shorter.
    ' Similar to List.RemoveAt, but for arrays.
     _
    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):

    Dim a() As String = {"Albert", "Betty", "Carlos", "David"}
    a.RemoveAt(0)    ' Remove first element => {"Betty", "Carlos", "David"}
    a.RemoveAt(1)    ' Remove second element => {"Betty", "David"}
    a.RemoveAt(UBound(a))    ' Remove last element => {"Betty"}
    

    Removing First or Last element is common, so here are convenience routines for doing so (I like code that expresses my intent more readably):

     _
    Public Sub DropFirstElement(Of T)(ByRef a() As T)
        a.RemoveAt(0)
    End Sub
    
     _
    Public Sub DropLastElement(Of T)(ByRef a() As T)
        a.RemoveAt(UBound(a))
    End Sub
    

    Usage:

    a.DropFirstElement()
    a.DropLastElement()
    

    And as Heinzi said, if you find yourself doing this, instead use List(Of T), if possible. List already has "RemoveAt" subroutine, and other routines useful for inserting/deleting elements.

提交回复
热议问题