将列表框项目分为两部分

时间:2016-07-16 04:36:32

标签: vb.net list split listbox

我有一个包含随机项目的列表框,我想把它分成两部分并将每个部分放在一个列表框中。我能够做到这一点,但我得到了一个非常混乱的代码,无法在网上找到任何帮助,所以我只想询问是否有其他方法可以做到这一点。这是我的代码。

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        'items count
        Dim count_listbox1 As Integer = ListBox1.Items.Count - 1

        'half the count - 1 (im going to use it on the for loop)
        Dim metade_listbox1_1 As Integer = (count_listbox1 / 2) - 1

        'half the count
        Dim metade_listbox1_2 As Integer = (count_listbox1 / 2)


        ' ( first part of the listbox)
        For i = 0 To metade_listbox1_1
            list1.Items.Add(ListBox1.Items.Item(i)) 'list1 - listbox that contains 1 half
        Next

        ' (second part of the listbox items)
        For i = metade_listbox1_2 To count_listbox1
            list2.Items.Add(ListBox1.Items.Item(i)) 'list2 - listbox that contains 2 half 
        Next

        'check if number of items its even or odd, if odd, deletes the first item of the list2, 
        'because its the same as the last item from list1
        If eo = False Then
            list2.Items.Remove(list2.Items.Item(0))
        End If
    End Sub

1 个答案:

答案 0 :(得分:1)

有很多方法可以拆分列表。以下将逐个均匀地分发它们

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    For i = 0 To ListBox1.Items.Count - 1
        Dim lstbx As ListBox = If(i Mod 2 = 0, list1, list2)
        lstbx.Items.Add(ListBox1.Items.Item(i))
    Next
End Sub  

结果更像您的结果的方法是这样的(需要导入System.Linq) 请注意,我首先将size2设置为计数的一半,以便在项目数为奇数的情况下具有额外项目。

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim size2 as Integer = ListBox1.Items.Count / 2
    Dim size1 as Integer = ListBox1.Items.Count - size2

    list1.Items.AddRange(ListBox1.Items.GetRange(0, size1))
    list2.Items.AddRange(ListBox1.Items.GetRange(size1, size2))
End Sub