I开发者_如何学Python am using VB.NET and .NET framework 3.0
I am currently sorting a list like this:
lstPeople.Sort(Function(p1, p2) p1.LName.CompareTo(p2.LName))
However, now I want to sort by FName as well after the LName. So it sorts first by last name and then by first name.
Is this possible?
Is this possible?
Yes, just write a comparer that implements the ordering that you want. So compare the last name first; if they are not equal return the result of CompareTo
and if they are not equal return the comparison between the first names.
Yeah it's possible.
I think the best way, if you can change the "People" class, create you own CompareTo()
function.
Private Function CompareTo(p2 As People) As Integer
Dim i As Int32 = Me.LName.CompareTo(p2.LName)
If i = 0 Then
Return Me.FName.CompareTo(p2.FName)
End If
Return i
End Function
then use it :
lstPeople.Sort(Function(p1, p2) p1.CompareTo(p2))
EDIT : Convert to VB.NET.
Try
Public Class PeopleComparer
Implements IComparer(Of People)
Public Function Compare(x As People, y As People) As Integer
Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
End Function
End Class
and
lstPeople.Sort(New PeopleComparer())
Bala R's answer is essentially correct, but I had to provide the compiler with a little more information to get past the compiler error you were seeing:
Public Class PeopleComparer
Implements IComparer(Of People)
Public Function Compare(x As People, y As People) As Integer Implements IComparer(Of People).Compare
Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
End Function
End Class
and
lstPeople.Sort(New PeopleComparer())
Implements System.Collections.Generic.IComparer(Of People).Compare
have to be added to the function. Stub is generated by typing enter key after IComparer(Of People)
Public Class PeopleComparer
Implements IComparer(Of People)
Public Function Compare(x As People, y As People) As Integer Implements System.Collections.Generic.IComparer(Of People).Compare
Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
End Function
End Class
精彩评论