How to create a dictionary with key type point (x, y) and value type string in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class Point
    Public ReadOnly Property X As Integer
    Public ReadOnly Property Y As Integer

    Public Sub New(x As Integer, y As Integer)
        Me.X = x
        Me.Y = y
    End Sub

    ' Override Equals
    Public Overrides Function Equals(obj As Object) As Boolean
        If TypeOf obj Is Point Then
            Dim other As Point = CType(obj, Point)
            Return Me.X = other.X AndAlso Me.Y = other.Y
        End If
        Return False
    End Function

    ' Override GetHashCode
    Public Overrides Function GetHashCode() As Integer
        Return HashCode.Combine(X, Y)
    End Function

    ' Override ToString
    Public Overrides Function ToString() As String
        Return $"({X}, {Y})"
    End Function
End Class

Module Program
    Sub Main()
		Dim dict As New Dictionary(Of Point, String)()

        dict(New Point(2, 7)) = "A"
        dict(New Point(3, 6)) = "B"
        dict(New Point(0, 0)) = "C"

        ' Print x and y separately
        For Each entry In dict
            Dim key As Point = entry.Key
            Dim value As String = entry.Value
            Console.WriteLine($"x: {key.X}, y: {key.Y} => {value}")
        Next
    End Sub
End Module



' run:
'   
' 
' x: 2, y: 7 => A
' x: 3, y: 6 => B
' x: 0, y: 0 => C
'

 



answered Aug 10 by avibootz
...