Question
I often need to sort a dictionary of keys and values by its values instead of its keys. For example, I may have a dictionary that stores words and their frequencies, and I want to order the entries by frequency.
SortedList works well when sorting by a single key, such as frequency, but then I still need a way to map that sorted result back to the original word.
SortedDictionary sorts by key, not by value.
Some solutions use a custom class, but is there a cleaner and more idiomatic way in C# to sort a dictionary by value?
Example idea:
var wordFrequencies = new Dictionary<string, int>
{
{ "apple", 4 },
{ "banana", 2 },
{ "orange", 7 }
};
How can this dictionary be ordered by frequency?
Short Answer
By the end of this page, you will understand how to sort a Dictionary<TKey, TValue> by value in C#, why dictionaries are not inherently value-ordered, and how LINQ is commonly used to create ordered results. You will also learn when to keep the result as an ordered sequence and when to convert it into another collection type.
Concept
A Dictionary<TKey, TValue> in C# is designed for fast lookup by key, not for maintaining sorted order.
That means two important things:
- A dictionary does not naturally sort by value.
- If you want items ordered by value, you usually create a new ordered sequence from the dictionary.
The most common way to do this is with LINQ:
var sorted = myDictionary.OrderBy(pair => pair.Value);
This works because each dictionary entry is a KeyValuePair<TKey, TValue>, which has:
pair.Keypair.Value
So when you call OrderBy(pair => pair.Value), you are saying:
"Take all dictionary entries and sort them using each entry's value."
This matters in real programming because many useful tasks depend on ordering by value:
- showing the most frequent word
- ranking users by score
- sorting products by price
- ordering error codes by count
- displaying analytics from highest to lowest
A key idea here is that sorting a dictionary does not change what a dictionary is for. Once you sort it, the result is typically an IOrderedEnumerable<KeyValuePair<TKey, TValue>>, not a magically value-sorted dictionary.
Mental Model
Think of a dictionary like a labeled filing cabinet.
- The label on each drawer is the key.
- The content inside is the value.
A dictionary is optimized so you can quickly open the drawer labeled "apple" and get its value.
But if you ask:
"Show me all drawers ordered by what's inside them, not by their labels"
then the cabinet itself does not rearrange automatically.
Instead, you take out all the drawer-label-and-content pairs, lay them on a table, and sort them.
That is what LINQ does:
- dictionary = storage for fast access
OrderBy= create a sorted view of its entries
So, rather than thinking "How do I make the dictionary sort itself by value?", think:
"How do I produce an ordered sequence from the dictionary based on value?"
Syntax and Examples
The basic syntax is:
var sorted = dictionary.OrderBy(pair => pair.Value);
To sort in descending order:
var sortedDescending = dictionary.OrderByDescending(pair => pair.Value);
Example: sort words by frequency
using System;
using System.Collections.Generic;
using System.Linq;
var wordFrequencies = new Dictionary<string, int>
{
{ "apple", 4 },
{ "banana", 2 },
{ "orange", 7 },
{ "grape", 4 }
};
var sorted = wordFrequencies.OrderBy(pair => pair.Value);
foreach (var pair in sorted)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
Output:
banana: 2
apple: 4
grape: 4
orange: 7
This sorts entries from lowest frequency to highest.
Sort by value, then by key
Step by Step Execution
Consider this code:
using System;
using System.Collections.Generic;
using System.Linq;
var scores = new Dictionary<string, int>
{
{ "Alice", 90 },
{ "Bob", 75 },
{ "Charlie", 95 }
};
var orderedScores = scores.OrderBy(pair => pair.Value);
foreach (var pair in orderedScores)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
Here is what happens step by step:
-
A dictionary called
scoresis created.Alice→90Bob→75Charlie→95
-
scores.OrderBy(pair => pair.Value)is executed.
Real World Use Cases
Sorting a dictionary by value is common when the values represent some kind of ranking, count, or measurement.
Common examples
-
Word frequency analysis
- Count how many times each word appears, then show the most common words first.
-
Leaderboard systems
- Store player names and scores, then sort by score descending.
-
Product pricing reports
- Map product IDs to prices and sort to find cheapest or most expensive items.
-
Analytics dashboards
- Store event names and counts, then rank events by popularity.
-
Error monitoring
- Count exceptions by type and sort by frequency to identify the biggest problems.
-
Inventory tools
- Track item names and stock quantities, then sort by lowest stock first.
Example: leaderboard
var scores = new Dictionary<string, int>
{
{ "Mia", 1200 },
{ "Noah", 950 },
{ "Liam", 1400 }
};
var leaderboard = scores
.OrderByDescending(pair => pair.Value)
.ThenBy(pair => pair.Key);
Real Codebase Usage
In real C# projects, developers usually do not try to make the dictionary itself permanently sorted by value. Instead, they use a few common patterns.
1. Keep dictionary for lookup, sort only when needed
var counts = GetWordCounts();
var topItems = counts.OrderByDescending(x => x.Value).Take(10);
This is efficient and readable.
2. Use secondary sorting for deterministic results
When values tie, sort by key too:
var ordered = counts
.OrderByDescending(x => x.Value)
.ThenBy(x => x.Key);
This prevents ambiguous output order.
3. Combine with filtering
Developers often filter before sorting:
var importantErrors = errorCounts
.Where(x => x.Value > 5)
.OrderByDescending(x => x.Value);
4. Use Take for top-N queries
var top5Words = wordCounts
.OrderByDescending(x => x.Value)
.Take(5)
.ToList();
This pattern appears in dashboards, reports, and API endpoints.
5. Materialize results when needed
If you will iterate multiple times, convert the result:
Common Mistakes
1. Expecting Dictionary to stay value-sorted
Beginners sometimes think this:
var sorted = myDictionary.OrderBy(x => x.Value);
means the dictionary itself has now been rearranged.
It has not. sorted is a new ordered sequence.
2. Converting back to Dictionary and expecting order guarantees
var sortedDictionary = myDictionary
.OrderBy(x => x.Value)
.ToDictionary(x => x.Key, x => x.Value);
This creates a new dictionary, but a dictionary is still not conceptually a value-sorted collection.
If you need ordered iteration, prefer:
var sortedList = myDictionary.OrderBy(x => x.Value).ToList();
3. Forgetting descending order for rankings
For leaderboards, this is wrong if you want highest first:
var topPlayers = scores.OrderBy(x => x.Value);
Use:
var topPlayers = scores.OrderByDescending(x => x.Value);
4. Ignoring ties
Comparisons
| Option | Sorts by | Best for | Notes |
|---|---|---|---|
Dictionary<TKey, TValue> | No guaranteed value sorting | Fast key lookup | Most common general-purpose dictionary |
SortedDictionary<TKey, TValue> | Key | Always keeping keys sorted | Does not sort by value |
SortedList<TKey, TValue> | Key | Key-sorted collection with index access | Also sorts by key, not value |
OrderBy(x => x.Value) on a dictionary | Value | Producing ordered output | Returns an ordered sequence |
List<KeyValuePair<TKey, TValue>> |
Cheat Sheet
// Sort ascending by value
var sorted = dictionary.OrderBy(x => x.Value);
// Sort descending by value
var sortedDesc = dictionary.OrderByDescending(x => x.Value);
// Sort by value, then key
var sortedWithTieBreak = dictionary
.OrderBy(x => x.Value)
.ThenBy(x => x.Key);
// Convert to list
var list = dictionary
.OrderBy(x => x.Value)
.ToList();
// Top 5 by value
var top5 = dictionary
.OrderByDescending(x => x.Value)
.Take(5)
.ToList();
Key rules
Dictionary<TKey, TValue>is optimized for key lookup.SortedDictionary<TKey, TValue>sorts by key, not value.OrderBy(x => x.Value)creates an ordered sequence.- Use
ThenBy(...)to break ties. - Use
ToList()if you need to store the sorted result.
Common edge cases
- Equal values may need a secondary sort.
- Converting back to
Dictionarydoes not make it a value-sorted collection. - Use descending order for rankings and leaderboards.
FAQ
How do I sort a dictionary by value in C#?
Use LINQ:
var sorted = dictionary.OrderBy(x => x.Value);
Can a Dictionary in C# be permanently sorted by value?
Not directly. A dictionary is not designed as a value-sorted collection. Usually you create a sorted sequence from it.
What is the difference between SortedDictionary and sorting by value?
SortedDictionary sorts by key. If you want value-based ordering, use LINQ such as OrderBy(x => x.Value).
How do I sort a dictionary by highest value first?
Use:
var sorted = dictionary.OrderByDescending(x => x.Value);
How do I handle duplicate values when sorting?
Add a secondary sort key:
var sorted = dictionary.OrderBy(x => x.Value).ThenBy(x => x.Key);
Should I convert the sorted result back into a dictionary?
Usually no. If you need ordered iteration, a List<KeyValuePair<TKey, TValue>> is often a better result type.
Is LINQ the usual way to sort a dictionary by value in modern C#?
Mini Project
Description
Build a small word-frequency report tool. You will start with a sentence, count how many times each word appears, and then sort the dictionary by frequency so the most common words appear first. This mirrors real tasks such as text analysis, search indexing, and analytics summaries.
Goal
Create a C# program that counts words and prints them ordered by frequency from highest to lowest.
Requirements
Requirement 1
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Array Initialization Syntaxes Explained
Learn all common C# array initialization syntaxes with examples, rules, comparisons, and mistakes beginners often make.