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
Leave a comment

1 Comment

  1. Experts Comment

     /  September 26, 2010

    Dictionary can be easily sorted by its value using LINQ. Below link provide good details about the same.

    http://www.a2zmenu.com/CSharp/How-to-sort-CSharp-dictionary-by-value.aspx

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: