2

尝试按对象名称对数组列表进行排序

Dim ObjList as new arraylist
Dim TextBox1 as new textbox
Textbox1.name = "CCC"
Dim TextBox2 as new textbox
Textbox1.name = "AAA"
Dim TextBox3 as new textbox
Textbox1.name = "BBB"
ObjList.add(TextBox1)
ObjList.add(TextBox2)
ObjList.add(TextBox3)
ObjList.sort()

排序会产生错误。我将如何按名称对文本框进行排序,使其看起来像 AAA BBB CCC

谢谢

4

1 回答 1

7

您必须创建一个IComparer并将其传递给该Sort方法:

Class TextBoxComparer 
    Implements IComparer

    Public Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
        Return String.Compare(x.Name, y.Name)
    End Function

End Class

...

ObjList.Sort(New TextBoxComparer())

或者,如果您可以切换到List(Of TextBox),一个匿名函数(匹配Comparison(Of T)委托)也可以:

Dim ObjList As New List(Of TextBox)

...

ObjList.Sort(Function(x, y) String.Compare(x.Name, y.Name))
于 2012-11-28T15:05:45.887 回答