2

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

1
  • You've set Textbox1.Name three times - in case that is actually what you meant I have left it to you to edit your post. Also, what version of Visual Studio are you using. Commented Nov 28, 2012 at 16:20

1 Answer 1

7

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.