簡體   English   中英

如何從VB.Net中的數組中刪除值

[英]How to delete values from array in VB.Net

我有一個包含這些值的數組

{1, 5, 16, 15}

我想刪除第一個元素,以便現在的值。

{Null, 5, 16, 15}

然后,我想再次檢查並刪除第一個非空值,這將產生:

{Null, Null, 16, 15}

我該如何在VB中編寫代碼?

嘗試這個

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

就像@Andrew Morton提到的那樣,普通的Integer值不能為Null(無)。 有一個可為空的整數類型Integer? 可以將其設置為Null值(在這種情況下為Nothing)。 以上代碼僅在數組為Integer? 值而不是Integer數值。

VB.NET中的Integer是值類型 如果嘗試將其設置為Nothing (在VB.NET中沒有null ),則它將采用其默認值,對於Integer,該值為零。

您可以改用Nullable(Of Integer) ,也可以將其寫為Integer?

作為演示:

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

輸出:

五,十六,十五
16、15、15
沒事沒事15

如果您對與C#的區別感興趣,請參見例如, 為什么不能在VB.NET中將Nothing分配給Integer?

嘗試這個:

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

您可以使用如下形式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM