[英]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? 我该如何在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). 就像@Andrew Morton提到的那样,普通的Integer值不能为Null(无)。 There is a nullable integer type
Integer?
有一个可为空的整数类型
Integer?
which can be set to a Null value (Nothing in this case). 可以将其设置为Null值(在这种情况下为Nothing)。 The above code would only be appropriate if the array was of
Integer?
以上代码仅在数组为
Integer?
values rather than an Integer
value. 值而不是
Integer
数值。
An Integer in VB.NET is a value type . VB.NET中的Integer是值类型 。 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. 如果尝试将其设置为
Nothing
(在VB.NET中没有null
),则它将采用其默认值,对于Integer,该值为零。
You can use a Nullable(Of Integer)
instead, which can also be written as Integer?
您可以改用
Nullable(Of Integer)
,也可以将其写为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, 1516、15、15
Nothing, Nothing, Nothing, 15没事没事15
If you are interested in the difference from C# see, eg, Why can you assign Nothing to an Integer in VB.NET? 如果您对与C#的区别感兴趣,请参见例如, 为什么不能在VB.NET中将Nothing分配给Integer?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.