Sorting a C# dictionary by value

This is fairly simple: create a list to hold your dictionary’s objects and use a delegate to provide a custom sorting mechanism.

Dictionary<int, double> myDictionary = new Dictionary<int, double>();

public Dictionary<int, double> SortMyDictionaryByValue()
{
    List<KeyValuePair<int, double>> tempList = new List<KeyValuePair<int, double>>(myDictionary);

    tempList.Sort(delegate(KeyValuePair<int, double> firstPair, KeyValuePair<int, double> secondPair)
                    {
                        return firstPair.Value.CompareTo(secondPair.Value);
                    }
                 );

    Dictionary<int, double> mySortedDictionary = new Dictionary<int, double>();
    foreach(KeyValuePair<int, double> pair in tempList)
    {
        mySortedDictionary.Add(pair.Key, pair.Value);
    }

    return mySortedDictionary;
}
Advertisements