從數組值我有一個包含這些值如何刪除在VB.Net
{1, 5, 16, 15}
我要刪除的第一個元素,這樣的數值現在的數組。
{Null, 5, 16, 15}
那麼我想再次經歷和刪除第一個非空值,這將產生:
{Null, Null, 16, 15}
如何在VB代碼呢?
從數組值我有一個包含這些值如何刪除在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莫頓提到的,正常的整數值不能爲Null(沒有)。有一個可爲空的整數類型Integer?
,它可以設置爲空值(在這種情況下爲Nothing)。如果數組的值爲Integer?
而不是Integer
的值,則上述代碼僅適用。
您是否測試過該代碼?你有沒有注意到你設置爲'Nothing'的元素是以零而不是'Nothing'出現的? –
我無法測試該代碼。如果他想將它們設置爲Null,我認爲他正在使用「Integer?」。我應該澄清,我的錯誤。 –
VB.NET中的Integer是值類型。如果您嘗試將其設置爲Nothing
(在VB.NET中沒有null
),那麼它將採用其默認值,對於整數爲零。
您可以使用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
輸出:
沒什麼,5,16,15
沒有,沒有,16個,15
沒什麼,沒什麼,沒什麼,15
如果您對與C#的區別感興趣,請參閱Why can you assign Nothing to an Integer in VB.NET?
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
什麼是'myArray'的元素的類型? –