How do you sort a dictionary by value?

前端 未结 19 2640
误落风尘
误落风尘 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条回答
  •  执念已碎
    2020-11-22 04:20

    On a high level, you have no other choice than to walk through the whole Dictionary and look at each value.

    Maybe this helps: http://bytes.com/forum/thread563638.html Copy/Pasting from John Timney:

    Dictionary s = new Dictionary();
    s.Add("1", "a Item");
    s.Add("2", "c Item");
    s.Add("3", "b Item");
    
    List> myList = new List>(s);
    myList.Sort(
        delegate(KeyValuePair firstPair,
        KeyValuePair nextPair)
        {
            return firstPair.Value.CompareTo(nextPair.Value);
        }
    );
    

提交回复
热议问题