Home >Backend Development >C++ >How Can I Efficiently Sort a Dictionary by Value Using LINQ?

How Can I Efficiently Sort a Dictionary by Value Using LINQ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-28 08:07:09851browse

How Can I Efficiently Sort a Dictionary by Value Using LINQ?

LINQ high -efficiency dictionary value sorting

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

This code creates a new dictionary

, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn