Sort a List of Object in VB.NET
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!
Thanks.
Solution 1:
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:
theList.Sort(Function(x, y) x.age.CompareTo(y.age))
Using the OrderBy
extension method:
theList = theList.OrderBy(Function(x) x.age).ToList()
Solution 2:
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)