Having seen many a discussion about how to remove a row from an Array, and being as there's no native way like in a dictionary object, a few method seemed to have evolved.

Below I'll outline my own way of acheiving such a task. The example below is with a 2 dimensional array called sArray, initially Dim'd as sArray(6,0) and then stored in a session variable called "sArray". Obviously you could pass the array into the sub as well.


Public Shared Sub deleteArrayItem(ByVal ID As Integer)

        ' Declare the array and bring it in from the Sub or Session
        Dim sArray(,) As String = HttpContext.Current.Session("sArray")
        ' The value we're looking to remove, be it an Integer, string etc.

        Dim delIndex As Integer

        ' Find the array index that matches the above variable
        For i As Integer = 0 To sArray.GetUpperBound(1)
            If sArray(0, i) = ID Then
                delIndex = i
                Exit For
            End If
        Next

        ' From the point of the index we wish to loop through until the penultimate item
        For i As Integer = delIndex To sArray.GetUpperBound(1)
            If i < sArray.GetUpperBound(1) Then
                sArray(0, i) = sArray(0, i + 1)
                sArray(1, i) = sArray(1, i + 1)
                sArray(2, i) = sArray(2, i + 1)
                sArray(3, i) = sArray(3, i + 1)
                sArray(4, i) = sArray(4, i + 1)
                sArray(5, i) = sArray(5, i + 1)
                sArray(6, i) = sArray(6, i + 1)
            End If
        Next

        ' Redim the array to have one less index.
        ReDim Preserve sArray(6, sArray.GetUpperBound(1) - 1)

        HttpContext.Current.Session("sArray") = sArray

End Sub


So, ID is what we're trying to match from the array, obviously we need to know the item we wish to remove, either via a string or some other Array variable. If you know the index you wish to remove then simply remove the top For Loop as this simply finds the array index to start from.

Next we loop through the array starting at the record we wish to delete and copy the index above over the current record. Once this has finished, just redim the array with 1 lower on the upper bound and you have now effectly deleted the item from the array.

         © 2009 pureCygnet