How do you sort a dictionary by value?

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

    Suppose we have a dictionary as

       Dictionary dict = new Dictionary();
       dict.Add(21,1041);
       dict.Add(213, 1021);
       dict.Add(45, 1081);
       dict.Add(54, 1091);
       dict.Add(3425, 1061);
       sict.Add(768, 1011);
    

    1) you can use temporary dictionary to store values as :

            Dictionary dctTemp = new Dictionary();
    
            foreach (KeyValuePair pair in dict.OrderBy(key => key.Value))
            {
                dctTemp .Add(pair.Key, pair.Value);
            }
    

提交回复
热议问题