How to sort a list of objects bu multiple comparison in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class Car
	Implements IComparable(Of Car)
	
    Public Property Name As String
	Public Property Price As Decimal  
			
	Public Function CompareTo(ByVal other As Car) As Integer _
        Implements System.IComparable(Of Car).CompareTo

        Dim compare As Integer
		
		compare = String.Compare(Me.Name, other.Name, True)

        If compare = 0 Then
            compare = Me.Price.CompareTo(other.Price)

            compare = -compare
        End If

        Return compare
    End Function
End Class	
		
Public Module Module1
	Public Sub Main()
		Dim cars As New List(Of Car) From
    	{
			New Car With {.Name = "New 2020 Honda HR‑V SUV", .Price = 30010},
			New Car With {.Name = "2020 Volvo XC60", .Price = 47400},
			New Car With {.Name = "2020 Audi Q3", .Price = 35695},
			New Car With {.Name = "2020 Nissan Murano", .Price = 32625}
    	}

    	cars.Sort()

		For Each theCar As Car In cars
			Console.WriteLine(theCar.Name)
			Console.WriteLine(theCar.Price.ToString & " ")
			Console.WriteLine()
		Next
	End Sub
End Module
	
	

' run:
'
' 2020 Audi Q3
' 35695 

' 2020 Nissan Murano
' 32625 

' 2020 Volvo XC60
' 47400 

' New 2020 Honda HR‑V SUV
' 30010
'

 



answered May 5, 2020 by avibootz
...