如何在VB.NET中从数组中删除一个项目?

32

如何从一个VB.NET数组中删除一个元素?

12个回答

0

这个方法怎么样:
获取一个返回数组的方法,例如 tempArray
tempArray 应该比您的数组少至少 1 个元素,例如 permArray
该方法应该接受一个整数参数(这将是不需要的元素的索引),例如 ommitIndex 和您的 permArray

在该方法中,将除了位置 ommitIndex 外的所有元素从 permArray 复制到 tempArray

该方法返回 tempArray,因此使用该方法更新 permArray
这是一个代码片段:

Function updateArray(ommitIndex As Integer, array() As String) As Array
    Dim tempArray(array.Length - 2) As String
    Dim counter As Integer = 0

    For i As Integer = 0 To (array.Length - 1)
        If (i <> ommitIndex) Then
            tempArray(counter) = array(i)
            counter += 1
        End If
    Next

    Return tempArray
End Function

0

看起来比实际要复杂...

    Dim myArray As String() = TextBox1.Lines
    'First we count how many null elements there are...
    Dim Counter As Integer = 0
    For x = 0 To myArray.Count - 1
        If Len(myArray(x)) < 1 Then
            Counter += 1
        End If
    Next
    'Then we dimension an array to be the size of the last array
    'minus the amount of nulls found...
    Dim tempArr(myArray.Count - Counter) As String

    'Indexing starts at zero, so let's set the stage for that...
    Counter = -1

    For x = 0 To myArray.Count - 1
        'Set the conditions for the new array as in
        'It .contains("word"), has no value, length is less than 1, ect.
        If Len(myArray(x)) > 1 Then
            Counter += 1
            'So if a value is present, we move that value over to
            'the new array.
            tempArr(Counter) = myArray(x)
        End If
    Next

现在你可以将tempArr分配回原始数组,或者进行任何你需要的操作,例如:

TextBox1.Lines = tempArr (现在你有一个没有空行的文本框)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接