gpt4 book ai didi

vb.net - 如何从 VB.NET 中的数组中删除项目?

转载 作者:行者123 更新时间:2023-12-03 10:23:43 25 4
gpt4 key购买 nike

如何从 VB.NET 中的数组中删除项目?

最佳答案

正如 Heinzi 所说,数组的大小是固定的。为了“删除项目”或“调整大小”,您必须创建一个具有所需大小的新数组,并根据需要复制您需要的项目。
这是从数组中删除项目的代码:

<System.Runtime.CompilerServices.Extension()> _
Function RemoveAt(Of T)(ByVal arr As T(), ByVal index As Integer) As T()
Dim uBound = arr.GetUpperBound(0)
Dim lBound = arr.GetLowerBound(0)
Dim arrLen = uBound - lBound

If index < lBound OrElse index > uBound Then
Throw New ArgumentOutOfRangeException( _
String.Format("Index must be from {0} to {1}.", lBound, uBound))

Else
'create an array 1 element less than the input array
Dim outArr(arrLen - 1) As T
'copy the first part of the input array
Array.Copy(arr, 0, outArr, 0, index)
'then copy the second part of the input array
Array.Copy(arr, index + 1, outArr, index, uBound - index)

Return outArr
End If
End Function
你可以这样使用它:
Module Module1

Sub Main()
Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1)
End Sub
End Module
上面的代码从数组中删除了第二个元素 ( "mno" ) [其索引为 1]。
您需要在 .NET 3.5 或更高版本中进行开发才能使用扩展方法。
如果您使用的是 .NET 2.0 或 3.0,则可以这样调用该方法
arr = RemoveAt(arr, 1)
我希望这是你所需要的。
更新
在基于 ToolMakerSteve's comment 运行测试后,由于函数声明中使用了 ByVal,初始代码似乎没有修改您要更新的数组。但是,编写 arr = arr.RemoveAt(1)arr = RemoveAt(arr, 1) 之类的代码确实会修改数组,因为它将修改后的数组重新分配给原始数组。
在下面找到用于从数组中删除元素的更新方法(子程序)。
<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef arr As T(), ByVal index As Integer)
Dim uBound = arr.GetUpperBound(0)
Dim lBound = arr.GetLowerBound(0)
Dim arrLen = uBound - lBound

If index < lBound OrElse index > uBound Then
Throw New ArgumentOutOfRangeException( _
String.Format("Index must be from {0} to {1}.", lBound, uBound))

Else
'create an array 1 element less than the input array
Dim outArr(arrLen - 1) As T
'copy the first part of the input array
Array.Copy(arr, 0, outArr, 0, index)
'then copy the second part of the input array
Array.Copy(arr, index + 1, outArr, index, uBound - index)

arr = outArr
End If
End Sub
该方法的用法与原始方法类似,只是这次没有返回值,因此尝试从返回值分配数组将不起作用,因为没有返回任何内容。
Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1) ' Output: {"abc", "mno"} (works on .NET 3.5 and higher)
RemoveAt(arr, 1) ' Output: {"abc", "mno"} (works on all versions of .NET fx)
arr = arr.RemoveAt(1) 'will not work; no return value
arr = RemoveAt(arr, 1) 'will not work; no return value
注:
  • 我在这个过程中使用了一个临时数组,因为它使我的意图变得清晰,这正是 Redim Preserve 时 VB.NET 在幕后所做的。如果您想使用 Redim Preserve 就地修改数组,请参阅 ToolmakerSteve's answer
  • 这里写的 RemoveAt 方法是扩展方法。为了让它们工作,您必须将它们粘贴到 Module 中。如果将扩展方法放置在 Class 中,它们将无法在 VB.NET 中工作。
  • 重要 如果您要通过大量“删除”修改您的数组,强烈建议使用其他回答者建议的不同数据结构,例如 List(Of T)
  • 关于vb.net - 如何从 VB.NET 中的数组中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3448103/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com