在 VB.NET 中对对象列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11735902/
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
Sort a List of Object in VB.NET
提问by bombai
I have a list of passengers(object) where it has a differents properties..
我有一个乘客(对象)列表,其中有一个不同的属性..
passenger.name
passenger.age
passenger.surname
And I want to sort this list by age criterion, how can i do this?
我想按年龄标准对这个列表进行排序,我该怎么做?
I know in a list of integer/string List.Sort() works, but if is an object list, i dont know if its possible to sort by the value of a object property!
我知道在整数/字符串列表中 List.Sort() 有效,但如果是对象列表,我不知道是否可以按对象属性的值排序!
Thanks.
谢谢。
回答by Guffa
To sort by a property in the object, you have to specify a comparer or a method to get that property.
要按对象中的属性排序,您必须指定比较器或获取该属性的方法。
Using the List.Sort
method:
使用List.Sort
方法:
theList.Sort(Function(x, y) x.age.CompareTo(y.age))
Using the OrderBy
extension method:
使用OrderBy
扩展方法:
theList = theList.OrderBy(Function(x) x.age).ToList()
回答by user890332
If you need a custom string sort, you can create a function that returns a number based on the order you specify.
如果您需要自定义字符串排序,您可以创建一个函数,根据您指定的顺序返回一个数字。
For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:
例如,我想根据正面或扣环对图片进行排序。所以我做了以下事情:
Private Function sortpictures(s As String) As Integer
If Regex.IsMatch(s, "FRONT") Then
Return 0
ElseIf Regex.IsMatch(s, "SIDE") Then
Return 1
ElseIf Regex.IsMatch(s, "CLASP") Then
Return 2
Else
Return 3
End If
End Function
Then I call the sort function like this:
然后我像这样调用排序函数:
list.Sort(Function(elA As String, elB As String)
Return sortpictures(elA).CompareTo(sortpictures(elB))
End Function)
回答by Pierre-Olivier Pignon
you must implement IComparer interface.
您必须实现 IComparer 接口。
In this sample I've my custom object JSONReturn, I implement my class like this :
在这个示例中,我有我的自定义对象 JSONReturn,我像这样实现我的类:
Friend Class JSONReturnComparer
Implements IComparer(of JSONReturn)
Public Function Compare(x As JSONReturn, y As JSONReturn) As Integer Implements IComparer(Of JSONReturn).Compare
Return String.Compare(x.Name, y.Name)
End Function
End Class
I call my sort List method like this : alResult.Sort(new JSONReturnComparer())
我这样调用我的排序列表方法: alResult.Sort(new JSONReturnComparer())
Maybe it could help you
也许它可以帮助你