[VB6][VB.Net][C#.Net] 移除陣列元素

  • 22133
  • 0
  • VB6
  • 2008-11-30

摘要:[VB6][VB.Net][C#.Net] 移除陣列元素

繼上一篇,繼續玩下去,這次要玩的是移除陣列中的元素

VB6:土法煉鋼

Private Sub Command3_Click()
    Dim i As Long, j As Long
    i = CLng(Text5.Text)
    For j = i To UBound(arr) - 1 '刪
        arr(j) = arr(j + 1)
    Next j
    ReDim Preserve arr(UBound(arr) - 1)
    
    Text4.Text = ""
    For j = LBound(arr) To UBound(arr)
        If j <> 0 Then
            Text4.Text = Text4.Text & ","
        End If
        Text4.Text = Text4.Text & arr(j)
    Next j
End Sub

執行結果如下圖:眼尖的應該會發現7不見了

範例下載:VB6插入陣列.rar

.NET Framework 類別庫:

宣告成陣列的變數就能使用System.Array類別: System.Array.IList.Remove
動態陣列: System.Collections.ArrayList.Remove

根據jeff377前輩所指用List<T>效能比較好,所以不才的後學,也依jeff377前輩所指的MSDN試了一下,不知醬的寫法是不是jeff377前輩所講的方法

若有錯誤請前輩指教,感恩!

VB.NET2005:

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'Me.ListBox1.Items.Clear()
        Me.ListBox2.Items.Clear()
        ary = DelArray(ary, CInt(TextBox3.Text))
        For Each i As Integer In ary
            'Me.ListBox1.Items.Add(i)
            Me.ListBox2.Items.Add(i)
        Next
    End Sub

    Private Function DelArray(ByRef Ary() As Integer, ByVal insarr As Integer) As Integer()
        ' 使用 List 泛型類別  
        Dim lst As New List(Of Integer)
        For Each i As Integer In Ary
            lst.Add(i)
        Next
        lst.RemoveAt(insarr)
        'lst.Remove(insarr)
        Return lst.ToArray ' 將 List 的元素複製到新的陣列並回傳  
    End Function

執行畫面如下:

範例下載:VB.NET泛型插入陣列元素.rar

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo