Question

How to Sort a Dictionary by Value in C#

csharp.netsortingdictionary

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.Key
  • pair.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.

So the idiomatic C# approach is usually:

  1. Keep the original dictionary for fast lookup.
  2. Create a sorted view when you need ordered output.

This is cleaner than forcing value-based ordering into a collection type that was not built for it.

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?"

Take Quiz

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

If two values are the same, you can add a secondary sort:

var sorted = wordFrequencies
    .OrderBy(pair => pair.Value)
    .ThenBy(pair => pair.Key);

This is useful when you want stable, predictable ordering.

Convert to a list

If you want to store the ordered result:

var sortedList = wordFrequencies
    .OrderBy(pair => pair.Value)
    .ToList();

Now sortedList is a List<KeyValuePair<string, int>>.

Example: highest values first

var topWords = wordFrequencies
    .OrderByDescending(pair => pair.Value)
    .ThenBy(pair => pair.Key);

This is common for rankings and reports.

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:

  1. A dictionary called scores is created.

    • Alice → 90
    • Bob → 75
    • Charlie → 95
  2. scores.OrderBy(pair => pair.Value) is executed.

    • Each item in the dictionary is treated as a KeyValuePair<string, int>.
    • For each pair, LINQ reads the Value.
    • The values are 90, 75, and 95.
  3. LINQ sorts the entries by those values.

    • Bob has 75
    • Alice has 90
    • Charlie has 95
  4. The result is stored in orderedScores.

    • This is an ordered sequence.
    • It is not a Dictionary<string, int>.
  5. The foreach loop iterates over the sorted sequence.

Output:

Bob: 75
Alice: 90
Charlie: 95

Important detail

The original dictionary is still unchanged. If you later access:

Console.WriteLine(scores["Alice"]);

you still get fast key-based lookup. Sorting only affects the ordered view you created.

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);

This gives you a ranked list suitable for display in an app or API response.

Take Quiz

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:

var sortedResults = counts
    .OrderBy(x => x.Value)
    .ToList();

6. Guard against null collections

In larger codebases, validation matters:

if (counts == null)
{
    throw new ArgumentNullException(nameof(counts));
}

var ordered = counts.OrderBy(x => x.Value);

These patterns are preferred over custom sorting containers unless there is a very specific performance or design need.

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

If multiple items have the same value, output order may not be meaningful.

Better:

var ordered = counts
    .OrderBy(x => x.Value)
    .ThenBy(x => x.Key);

5. Sorting when lookup is all you need

If you only need:

var count = counts["apple"];

then sorting is unnecessary overhead.

6. Using the wrong collection type

If your main need is always sorted access by key, use SortedDictionary. If your need is always sorting by value, often the best answer is still:

  • keep a dictionary for storage
  • create a sorted sequence for display or reporting

Broken example

SortedDictionary<string, int> counts = new SortedDictionary<string, int>
{
    { "apple", 4 },
    { "banana", 2 },
    { "orange", 7 }
};

This sorts by string key (apple, banana, orange), not by the integer value.

Comparisons

OptionSorts byBest forNotes
Dictionary<TKey, TValue>No guaranteed value sortingFast key lookupMost common general-purpose dictionary
SortedDictionary<TKey, TValue>KeyAlways keeping keys sortedDoes not sort by value
SortedList<TKey, TValue>KeyKey-sorted collection with index accessAlso sorts by key, not value
OrderBy(x => x.Value) on a dictionaryValueProducing ordered outputReturns an ordered sequence
List<KeyValuePair<TKey, TValue>>Whatever you sort byStoring a custom sorted resultGood after calling ToList()

OrderBy vs OrderByDescending

MethodResult
OrderBy(x => x.Value)Lowest value first
OrderByDescending(x => x.Value)Highest value first

Dictionary vs ordered sequence

QuestionBetter choice
Do I need fast access by key?Dictionary<TKey, TValue>
Do I need to display items sorted by value?dictionary.OrderBy(x => x.Value)
Do I need the top 10 highest values?dictionary.OrderByDescending(x => x.Value).Take(10)
Do I need persistent sorting by key?SortedDictionary<TKey, TValue>
Take Quiz

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 Dictionary does 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#?

Yes. It is the most common and readable approach for this task.

Take Quiz

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

Take Quiz

Keep learning

Related questions

View more