Reputation: 731
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?
Upvotes: 1
Views: 2562
Reputation: 2111
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
Upvotes: 0
Reputation: 25023
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, e.g., Why can you assign Nothing to an Integer in VB.NET?
Upvotes: 3
Reputation: 343
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
Upvotes: 0
Reputation: 527
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.
Upvotes: 3