ArcSet
ArcSet

Reputation: 6860

VB.net Sort Arraylist By Objects Name

Trying to sort a arraylist by Objects name

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()

Sort creates a error. How would I sort the TextBoxs by Name so it looks like AAA BBB CCC

Thank you

Upvotes: 2

Views: 9884

Answers (1)

sloth
sloth

Reputation: 101072

You have to create an IComparer and pass it to the Sort method:

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())

Or, if you can switch to List(Of TextBox), an anonymous function (that matches the Comparison(Of T) delegate) will also do:

Dim ObjList As New List(Of TextBox)

...

ObjList.Sort(Function(x, y) String.Compare(x.Name, y.Name))

Upvotes: 7

Related Questions