VB.net按对象名称排序Arraylist

时间:2012-11-28 14:52:31

标签: vb.net sorting arraylist

尝试按对象名称

对arraylist进行排序
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()

排序会产生错误。我如何按名称对TextBox进行排序,看起来如此 AAA BBB CCC

谢谢

1 个答案:

答案 0 :(得分: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))