How do you sort a dictionary by value?

前端 未结 19 2357
误落风尘
误落风尘 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

    You can sort a Dictionary by value and save it back to itself (so that when you foreach over it the values come out in order):

    dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
    

    Sure, it may not be correct, but it works.

提交回复
热议问题