How to sort a dictionary first by value, then by key in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    /// <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 static Dictionary<TKey, TValue> SortMapByValueThenKey<TKey, TValue>(
        Dictionary<TKey, TValue> sourceMap)
        where TKey : IComparable<TKey>
        where TValue : IComparable<TValue>
    {
        return sourceMap
            .OrderBy(pair => pair.Value)     // Primary sort: Ascending by value
            .ThenBy(pair => pair.Key)        // Secondary sort: Ascending by key (tie-breaker)
            .ToDictionary(pair => pair.Key, pair => pair.Value);
    }

    static void Main()
    {
        // Initialize the dictionary with the requested values
        Dictionary<string, int> scores = new Dictionary<string, int>
        {
            { "Luna", 85 },
            { "Sofia", 92 },
            { "Charlie", 96 },
            { "Bella", 92 },
            { "Brock", 80 },
            { "Jolie", 96 },
            { "Bob", 92 },
            { "Eve", 92 }
        };

        // Sort the dictionary using our function
        Dictionary<string, int> sortedScores = SortMapByValueThenKey(scores);

        // Display the sorted results
        Console.WriteLine("Sorted by value (score), then by key (name):");
        Console.WriteLine("--------------------------------------------");
        foreach (KeyValuePair<string, int> kvp in sortedScores) {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}


/*
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
...