2012-11-28 37 views
2

試圖排序的ArrayList通過對象的名字VB.net排序的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() 

排序創建了一個錯誤。通過名稱TextBoxs所以它看起來像 AAA BBB CCC

我將如何排序

謝謝

+0

您已經設置了Textbox1.Name三次 - 萬一實際上您的意思是我已將它留給您編輯您的帖子。此外,你使用的是什麼版本的Visual Studio。 –

回答

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