.NET: Sort using multiple fields
Just documenting how to sort a list of objects using multiple sort fields, since I did not find good resource in internet. It is same process, implementing IComparable interface, but I found some people struggling when it comes to multiple fields. So here it goes, we have a simple class which is equipped with sort as below
First compare is done using Age and if they match we are comparing the salary, it just goes in same function
Public Class Employee Implements IComparable
Private mName As String Private mSalary As Double Private mAge As Integer Public Property Age() As Integer Get Return mAge End Get Set(ByVal value As Integer) mAge = value End Set End Property Public Property Name() As String Get Return mName End Get Set(ByVal value As String) mName = value End Set End Property
Public Property Salary() As Double Get Return mSalary End Get Set(ByVal value As Double) mSalary = value End Set End Property
Public Sub New(ByVal iName As String, ByVal iAge As Integer, ByVal iSalary As Double) mName = iName mAge = iAge mSalary = iSalary End Sub
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo Dim temployee As Employee = CType(obj, Employee) If Me.Age > temployee.Age Then Return 1 ElseIf Me.Age < temployee.Age Then Return -1 Else If Me.Salary > temployee.Salary Then Return 1 ElseIf Me.Salary < temployee.mSalary Then Return -1 Else Return 0 End If
End If End Function End Class
Lets Use it Dim empList As New List(Of Employee) empList.Add(New Employee("Jack", 21, 21400)) empList.Add(New Employee("Jane", 21, 21300)) empList.Add(New Employee("John", 22, 21200)) empList.Add(New Employee("Jessica", 21, 21500)) empList.Sort()
With saying that, I also want to show you Linq Method since that looks more easier
Dim SortedList = (From em As Employee In empList Select em Order By em.Age, em.Salary).ToList
Thats easier :) |
daff1316-3911-41a1-b2ee-d0178f2d078a|0|.0