How do you sort a dictionary by value?

前端 未结 19 2823
误落风尘
误落风尘 2020-11-22 03:51

I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequen

19条回答
  •  猫巷女王i
    2020-11-22 04:08

    The other answers are good, if all you want is to have a "temporary" list sorted by Value. However, if you want to have a dictionary sorted by Key that automatically synchronizes with another dictionary that is sorted by Value, you could use the Bijection class.

    Bijection allows you to initialize the collection with two existing dictionaries, so if you want one of them to be unsorted, and you want the other one to be sorted, you could create your bijection with code like

    var dict = new Bijection(new Dictionary(), 
                                   new SortedDictionary());
    

    You can use dict like any normal dictionary (it implements IDictionary), and then call dict.Inverse to get the "inverse" dictionary which is sorted by Value.

    Bijection is part of Loyc.Collections.dll, but if you want, you could simply copy the source code into your own project.

    Note: In case there are multiple keys with the same value, you can't use Bijection, but you could manually synchronize between an ordinary Dictionary and a BMultiMap.

提交回复
热议问题