How to sort a dictionary first by value, then by key in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Linq

Module MapSorter

    ''' <summary>
    ''' Sorts a dictionary first by value (ascending), then by key (ascending) as a tie-breaker.
    ''' </summary>
    ''' <typeparam name="TKey">The type of the dictionary keys (must be comparable).</typeparam>
    ''' <typeparam name="TValue">The type of the dictionary values (must be comparable).</typeparam>
    ''' <param name="sourceMap">The input dictionary to be sorted.</param>
    ''' <returns>A new Dictionary containing the entries sorted by value then key.</returns>
    Public Function SortMapByValueThenKey(Of TKey As IComparable(Of TKey), TValue As IComparable(Of TValue))(
        sourceMap As Dictionary(Of TKey, TValue)) As Dictionary(Of TKey, TValue)
        
        Return sourceMap.
            OrderBy(Function(pair) pair.Value).
            ThenBy(Function(pair) pair.Key).
            ToDictionary(Function(pair) pair.Key, Function(pair) pair.Value)
    End Function

    Sub Main()
        ' Initialize the dictionary with the requested values
        Dim scores As New Dictionary(Of String, Integer) From {
            {"Luna", 85},
            {"Sofia", 92},
            {"Charlie", 96},
            {"Bella", 92},
            {"Brock", 80},
            {"Jolie", 96},
            {"Bob", 92},
            {"Eve", 92}
        }

        ' Sort the dictionary using our function
        Dim sortedScores As Dictionary(Of String, Integer) = SortMapByValueThenKey(scores)

        ' Display the sorted results
        Console.WriteLine("Sorted by value (score), then by key (name):")
        Console.WriteLine("--------------------------------------------")
        For Each kvp As KeyValuePair(Of String, Integer) In sortedScores
            Console.WriteLine($"{kvp.Key}: {kvp.Value}")
        Next
    End Sub

End Module


' run:
'
' Sorted by value (score), then by key (name):
' --------------------------------------------
' Brock: 80
' Luna: 85
' Bella: 92
' Bob: 92
' Eve: 92
' Sofia: 92
' Charlie: 96
' Jolie: 96
' 

 



answered Oct 23 by avibootz
...