简体   繁体   中英

How to delete values from array in VB.Net

I have an array that contains these values

{1, 5, 16, 15}

I want to delete the first element so that the values are now.

{Null, 5, 16, 15}

I then want to go through again and delete the first non-null value, which would yield:

{Null, Null, 16, 15}

How do I code this in VB?

Try this

Dim i As Integer

For i = 0 To UBound(myArray)
    If Not IsNothing(myArray(i)) Then
        myArray(i) = Nothing
        Exit For
    End If
Next i

as @Andrew Morton mentioned, a normal Integer value cannot be Null (Nothing). There is a nullable integer type Integer? which can be set to a Null value (Nothing in this case). The above code would only be appropriate if the array was of Integer? values rather than an Integer value.

An Integer in VB.NET is a value type . If you try to set it to Nothing (there is no null in VB.NET) then it takes its default value, which for an Integer is zero.

You can use a Nullable(Of Integer) instead, which can also be written as Integer? .

As a demonstration:

Option Infer On
Option Strict On

Module Module1

    Sub Main()
        Dim myArray As Integer?() = {1, 5, 16, 15}

        For j = 1 To 3

            For i = 0 To UBound(myArray)
                If myArray(i).HasValue Then
                    myArray(i) = Nothing
                    Exit For
                End If
            Next i

            ' show the values...
            Console.WriteLine(String.Join(", ", myArray.Select(Function(n) If(n.HasValue, n.Value.ToString(), "Nothing"))))

        Next

        Console.ReadLine()

    End Sub

End Module

Outputs:

Nothing, 5, 16, 15
Nothing, Nothing, 16, 15
Nothing, Nothing, Nothing, 15

If you are interested in the difference from C# see, eg, Why can you assign Nothing to an Integer in VB.NET?

Try this:

Dim strArray() As Integer = {1, 5, 16, 15}
Dim strValues = strArray().ToList
Dim index = 3
strValues = strValues.Where(Function(s) s <> strValues(index)).ToArray

You can use something like this:

Dim myArray(3) As Integer
    myArray(0) = 1
    myArray(1) = 2
    myArray(2) = 3
    myArray(3) = 4
myArray = removeVal(myArray, 2)

-

Function removeVal(ByRef Array() As Integer, ByRef remove As Integer) As Integer()
    Array(remove) = Nothing
    Return Array
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM