How do you sort a dictionary by value?

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

    using System.Linq.Enumerable;
    ...
    List> myList = aDictionary.ToList();
    
    myList.Sort(
        delegate(KeyValuePair pair1,
        KeyValuePair pair2)
        {
            return pair1.Value.CompareTo(pair2.Value);
        }
    );
    

    Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).

    var myList = aDictionary.ToList();
    
    myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
    

提交回复
热议问题