How do you sort a dictionary by value?

前端 未结 19 2367
误落风尘
误落风尘 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
    慢半拍i (楼主)
    2020-11-22 04:21

    Looking around, and using some C# 3.0 features we can do this:

    foreach (KeyValuePair item in keywordCounts.OrderBy(key=> key.Value))
    { 
        // do something with item.Key and item.Value
    }
    

    This is the cleanest way I've seen and is similar to the Ruby way of handling hashes.

提交回复
热议问题