所以我需要在数组中获取一个项目的位置,并将其从数组中删除。
names = {"bob", "jeff", "harry", "carl"}
我会要求" jeff"例如,它会输出1。
然后我将使用项目的位置删除另一个数组中的相同位置。这是我需要编码的排序算法(没有Array.Sort(名称)),所以如果有更好的方法,我会很感激。
答案 0 :(得分:0)
你可以从数组中“删除”,但这不是我所说的效率。您必须使用Array.Resize
调整其大小,我相信在后台重新创建它。
Dim arrNames As String() = {"bob", "jeff", "harry", "carl"}
Dim sNameToSearchFor As String = "jeff"
For i As Integer = 0 To arrNames.Count - 1
'Make sure you're not trying to set the last value in the array to itself
If i <> arrNames.Count - 1 Then
arrNames(i) = arrNames(arrNames.Count - 1)
End If
'Resize the array by removing one and then exit the for loop
Array.Resize(arrNames, arrNames.Count - 1)
Exit For
Next
就像我说的那样,它并不理想,但它确实有效。
作为替代方案,可能与背景中的上述内容相同......
Dim arrNames As String() = {"bob", "jeff", "harry", "carl"}
Dim sNameToSearchFor As String = "jeff"
Dim nIndex As Integer = Array.IndexOf(arrNames, sNameToSearchFor)
'If it's -1 then it didn't find the object in the array
If nIndex <> -1 Then
'Check to see if it's at the end of the array
If nIndex <> arrNames.Count - 1 Then
arrNames(nIndex) = arrNames(arrNames.Count - 1)
End If
Array.Resize(arrNames, arrNames.Count - 1)
End If