How do you sort a dictionary by value?

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

    Required namespace : using System.Linq;

    Dictionary counts = new Dictionary();
    counts.Add("one", 1);
    counts.Add("four", 4);
    counts.Add("two", 2);
    counts.Add("three", 3);
    

    Order by desc :

    foreach (KeyValuePair kvp in counts.OrderByDescending(key => key.Value))
    {
    // some processing logic for each item if you want.
    }
    

    Order by Asc :

    foreach (KeyValuePair kvp in counts.OrderBy(key => key.Value))
    {
    // some processing logic for each item if you want.
    }
    

提交回复
热议问题