VB.net按对象名称排序Arraylist

Arc*_*Set 2 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()
Run Code Online (Sandbox Code Playgroud)

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

谢谢

slo*_*oth 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())
Run Code Online (Sandbox Code Playgroud)

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

Dim ObjList As New List(Of TextBox)

...

ObjList.Sort(Function(x, y) String.Compare(x.Name, y.Name))
Run Code Online (Sandbox Code Playgroud)