Home >Backend Development >C++ >How Can I Efficiently Sort a Dictionary by Value Using LINQ?
In program development, sorting is often required according to the value of the dictionary. For example, a dictionary storage word and its frequency need to be arranged in frequency reduction.
Although can be sorted by a single value (such as frequency), it cannot directly map back to the original key. Is based on the key, and the custom class is cumbersome.
Linq provides an elegant solution: SortedList
SortedDictionary
, and its key value pairs of the elevation sequence are arranged. It allows sorting according to different conditions, or a specific part of the sorting dictionary. For example, to find the first 10 most frequent words, you can use:
<code class="language-csharp">Dictionary<string, int> myDict = new Dictionary<string, int>(); myDict.Add("one", 1); myDict.Add("four", 4); myDict.Add("two", 2); myDict.Add("three", 3); var sortedDict = from entry in myDict orderby entry.Value ascending select entry;</code>
The above is the detailed content of How Can I Efficiently Sort a Dictionary by Value Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!