Several varieties on the <Of T> list

I 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, and also after LName. Therefore, he sorts first by last name, and then by first name.

Is it possible?

+4
source share
5 answers

Is it possible?

Yes, just write a comparator that implements the required order. Therefore, first compare the surname; if they are not equal, return the result of CompareTo , and if they are not equal, return the comparison between the names.

+1
source

Yes it is possible. I think the best way, if you can change the People class, is to create your 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.

+1
source

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()) 
0
source

Implements System.Collections.Generic.IComparer(Of People).Compare must be added to the function. A piece is generated by entering an 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 
0
source

Bala R's answer is mostly correct, but I had to give the compiler a bit more information to get past the compiler error you saw:

 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()) 
0
source

Source: https://habr.com/ru/post/1346245/


All Articles