我在面板上有一组按钮,我希望能够构建这些按钮的集合,然后按钮上的文本对按钮进行排序。但是,我被卡住了。这是我到目前为止所做的,但我无法弄清楚如何排序。
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim btn1 As Control
Dim btnArray(0 To 3) As Button
btnArray(0) = btnAll
btnArray(1) = btnWine
btnArray(2) = btnBeer
btnArray(3) = btnNonAlcoholic
For Each btn1 In btnArray
Next
End Sub
答案 0 :(得分:1)
您可以使用简单的手动冒泡排序:
Dim Changed as Boolean = False
Do
Changed = False
For i = 0 to btnArray.Count - 2
If btnArray(i).Text > btnArray(i+1).Text Then '< > work for strings as well and they check 'position' in the alphabet. So "A" < "B" and so on
'If order is wrong, switch the two buttons
Dim temp as Button = btnArray(i+1)
btnArray(i + 1) = btnArray(i)
btnArray(i) = temp
Changed = True
End If
Next
'Do this until no more switches are necessary
Loop Until Changed = False
这将订购您的按钮,并且对于少量按钮而言相当快。您也可以使用列表和自定义IComparer对象,只需使用自定义比较器调用List.Sort
即可。
请参阅此处,了解针对类似问题的此方法的实现:http://msdn.microsoft.com/en-us/library/cfttsh47%28v=vs.110%29.aspx
答案 1 :(得分:0)
使用LINQ:
btnArray = btnArray.OrderBy(Function(btn) btn.Text).ToArray