How do you sort a dictionary by value?

前端 未结 19 2366
误落风尘
误落风尘 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 03:56

    Use LINQ:

    Dictionary myDict = new Dictionary();
    myDict.Add("one", 1);
    myDict.Add("four", 4);
    myDict.Add("two", 2);
    myDict.Add("three", 3);
    
    var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
    

    This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead, you could also include StartsWith clause as well.

提交回复
热议问题