Thursday, January 17, 2008

sorting dictionary by value

oh hell how i didn't thought about this before!!!


public static Dictionary<string,long> SortDictionary(Dictionary<string,long> data)
{
  List<keyvaluepair<string,long>> result =
        new List<keyvaluepair<string,long>>(data);
  result.Sort(
    delegate(
      KeyValuePair<string,long> first,
      KeyValuePair<string,long> second)
        {
          return second.Value.CompareTo(first.Value);
        }
    );
  return data;
}

if you want the smallest amount be on top you need to switch the following line from:

return second.Value.CompareTo(first.Value);

to

return first.Value.CompareTo(second.Value);


the same method you can use also for: Dictionary<string,int> or Dictionary<string,string> or each value type of your choice.

--
happy sort of dictonary by value ;-) yes I love generics ... just sometimes I don't see through its possibilites

9 comments:

Anonymous said...

Brilliant solution!

Anonymous said...

excellent, just excellent!

Danke und Grüüüzi in die Schweiz aus Österreich!

Barry said...

Your code doesn't work.

You put data in the list, sort the list, but then return data.

So the dictionary returned isn't sorted.

You need to copy the contents of the sorted list back to a dictionary and return that.

Zach said...

Great work, Roni!
I turned it into a generic, not String-specific - just implement IComparable.
http://itbyz.blogspot.com/2008/07/net-dictionary-sort.html

Zach said...

Great code, Roni!
I used this as a basis for a generic sortable dictionary class:
http://itbyz.blogspot.com/2008/07/net-dictionary-sort.html

Anonymous said...

Works perfectly. Great work!

Thanks a lot!

Mehmet Atas said...

Barry is right. You should copy sorted values into a dictionary.
after List.Sort call, method should end like this

Dictionary<Option, int> sortedDic = new Dictionary<Option, int>();

foreach (KeyValuePair<Option, int> item in result) {
sortedDic.Add(item.Key, item.Value);
}

return sortedDic;

Anonymous said...

Cool, thnx dude.

Nicogis said...

you can use linq to objects

Dictionary d = new Dictionary();

d.Add(1,"Test 1");
d.Add(2,"Test 2");
d.Add(5,"Test 5");
d.Add(3,"Test 3");
d.Add(4, "Test 4");

var sortedDct = (from i in d orderby i.Value ascending select i);

sortedDct.Dump();

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge