VB.net 按对象名称对 Arraylist 排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13607897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.net Sort Arraylist By Objects Name
提问by ArcSet
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
排序会产生错误。我将如何按名称对文本框进行排序,使其看起来像 AAA BBB CCC
Thank you
谢谢
回答by sloth
You have to create an IComparerand pass it to the Sortmethod:
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:
或者,如果您可以切换到List(Of TextBox),匿名函数(匹配比较(Of T)委托)也将执行以下操作:
Dim ObjList As New List(Of TextBox)
...
ObjList.Sort(Function(x, y) String.Compare(x.Name, y.Name))

