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;
  • Disclaimer: The opinions expressed on this site are my own personal opinions and do not in any way represent my employer's view.
  • Twitter Updates

    Error: Twitter did not respond. Please wait a few minutes and refresh this page.

  • Archives

  • Advertisements