Updated on
To sort a dictionary by its values, we call OrderBy(x => x.Value) on it and keep the result with ToList(). What we get back is a list of key-value pairs in value order, since a Dictionary has no order of its own to sort.
We’ll look at that method and two others, and then benchmark all three on .NET 10.
Let’s begin.
What Does Sorting a Dictionary by Value Give Us?
A Dictionary holds key-value pairs in a hash table, which is why key lookup is so fast. It also means the dictionary has no order we can sort in place. Microsoft’s documentation for Dictionary<TKey,TValue> says it directly: “The order in which the items are returned is undefined.”
So sorting it by value always gives us a new collection. We read the pairs, order them by Value, and store them in a List<KeyValuePair<TKey,TValue>>. The list keeps the order we put it in, and the original dictionary stays as it was.
There are three ways to build that list. We can call LINQ’s OrderBy() method, write a LINQ query expression with an orderby clause, or copy the pairs into a list and call Sort() on it. All three return the same order for our sample.
What we shouldn’t do is copy the sorted pairs back into a new Dictionary, because nothing guarantees it will enumerate them in that order.
Before proceeding, we’ll create a simple dictionary of unordered values:
var dictionary = new Dictionary<string, string>
{
{ "1", "apple" },
{ "2", "orange" },
{ "3", "banana" },
{ "4", "grape" }
};
In this case, we are using the string type for both key and value in the dictionary. So the dictionary’s type is Dictionary<string,string>.
Using the OrderBy() Method
The first way is to use the OrderBy() method available in LINQ. We can directly invoke this method on the dictionary:
var sortedKeyValuePairs = dictionary.OrderBy(x => x.Value).ToList();
Here, we are passing a lambda expression x => x.Value to the OrderBy() method. This will order the dictionary by its value.Â
After ordering, we convert it to a list using the ToList() method. When we check the type of the list, it will be List<KeyValuePair<string,string>>. Here, each item in the list is represented as a KeyValuePair<TKey,TValue> type.
The reason we are not converting the ordered items back to the Dictionary<string,string> is that the dictionary cannot guarantee the same order upon enumeration. Hence, we need to preserve the ordered items in a list.
When we print the items in the list, we can see the ordered output:
1 apple 3 banana 4 grape 2 orange
If we want to sort the values in descending order, we can use the OrderByDescending()Â method.
When two pairs have the same value, OrderBy() keeps them in the order the dictionary handed them over, because it is a stable sort. With a dictionary, that order is the undefined one, so if ties matter, we sort them by key as well with ThenBy().
var sortedKeyValuePairs = dictionary
.OrderBy(x => x.Value)
.ThenBy(x => x.Key)
.ToList();
Our article on LINQ’s sorting operators covers ThenBy() and the rest of the family.
Using LINQ Query Expression
An alternative way is to use the LINQ Query Expression syntax. Let’s quickly look at how to do it:
var sortedKeyValuePairs = (
from keyValuePair in dictionary
orderby keyValuePair.Value ascending
select keyValuePair
).ToList();
Here, we are using the orderby clause on the keyValuePair.Value property. Additionally, we can use the ascending or descending keyword as per our needs.
Using the Sort() Method
The next way is to use the Sort() method. To use this method we need to first convert the dictionary to a list:
var sortedKeyValuePairs = dictionary.ToList();
And then, we can invoke the Sort() method on this list:
sortedKeyValuePairs.Sort((pair1, pair2) => pair1.Value.CompareTo(pair2.Value));
Please note that the Sort() method does not have a return value. It accepts a Comparison<T> delegate where we can pass the lambda expression. The Sort() method uses this expression to sort the list.
Which Sorting Method Is Fastest?
So far so good. Now, let’s benchmark these three ways and find out the most performant way. We’ll use the BenchmarkDotNet library to do the benchmark for us.
We’ll use three different dictionary sizes (1000, 10,000, and 100,000) for the benchmark. Also, we populate the dictionary with 36 char GUID values in the Generate() method of a DictionaryInput class:
public Dictionary<string, string> Generate(int count)
{
var dictionary = new Dictionary<string, string>();
for (var i = 0; i < count; i++)
{
dictionary.Add($"{i}", Guid.NewGuid().ToString());
}
return dictionary;
}
Let’s run the benchmark and wait for the result:
| Method | dictionaryInput | Mean | Error | StdDev | |-------------------------------------------- |---------------- |------------:|------------:|------------:| | SortDictionaryValueUsingLinqOrderBy | 1000 items | 152.7 us | 2.48 us | 2.32 us | | SortDictionaryValueUsingLinqQueryExpression | 1000 items | 150.5 us | 2.57 us | 2.40 us | | SortDictionaryValueUsingSortMethod | 1000 items | 172.2 us | 2.20 us | 2.26 us | | SortDictionaryValueUsingLinqOrderBy | 10000 items | 2,363.2 us | 45.63 us | 46.86 us | | SortDictionaryValueUsingLinqQueryExpression | 10000 items | 2,574.6 us | 49.40 us | 75.45 us | | SortDictionaryValueUsingSortMethod | 10000 items | 2,553.1 us | 37.93 us | 33.62 us | | SortDictionaryValueUsingLinqOrderBy | 100000 items | 46,078.0 us | 1,730.38 us | 5,102.06 us | | SortDictionaryValueUsingLinqQueryExpression | 100000 items | 43,529.7 us | 858.41 us | 1,633.22 us | | SortDictionaryValueUsingSortMethod | 100000 items | 40,621.7 us | 1,133.85 us | 3,289.51 us |
From the result, we can see that the three methods stay close at every size. For 1,000 items, OrderBy() and the query expression take about 150 us and Sort() takes about 170 us. The query expression compiles to the same OrderBy() call, so the two do the same work, even though this run shows them about 9 percent apart at 10,000 items.
As the dictionary grows, the time grows faster than the item count, which is what we expect from sorting. A hundred times more items costs a few hundred times more time. At 100,000 items, Sort() comes first in this run, ahead of the query expression and then OrderBy().
Since the differences are small, we can choose on readability. OrderBy() is the simplest to write and leaves the source untouched, so it stays our preferred option. Sort() makes sense when we already have a list and want to sort it in place.
How Do We Sort a Dictionary by Key or Keep It Sorted?
Sorting by key works the same way as sorting by value. We swap the lambda for OrderBy(x => x.Key) and get a list of pairs in key order.
When we want the collection itself to stay in key order, we use SortedDictionary<TKey,TValue> instead. It keeps its keys sorted as we add and remove entries. The cost is lookup speed. It is a binary search tree with O(log n) retrieval, where a Dictionary is close to O(1). A SortedList gives the same key order with less memory but slower inserts.
Neither of them sorts by value, so a value order still comes from one of the three methods above.
If we need that value order back in a dictionary, .NET 9 added OrderedDictionary<TKey,TValue>. It remembers the order we insert pairs in, so filling it from our sorted pairs gives a dictionary that enumerates by value. It doesn’t sort anything itself, though, and a pair we add later goes to the end.
Let’s try both with a small stock dictionary whose keys are out of order.
var stock = new Dictionary<string, int>
{
{ "orange", 12 },
{ "apple", 7 },
{ "banana", 30 }
};
var sortedByKey = stock.OrderBy(x => x.Key).ToList();
var sortedStock = new SortedDictionary<string, int>(stock);
foreach (var item in sortedStock)
{
Console.WriteLine(item.Key + " " + item.Value);
}
Both sortedByKey and sortedStock list the fruit alphabetically:
apple 7 banana 30 orange 12
And for our original dictionary, the value order survives in an OrderedDictionary.
var orderedByValue = new OrderedDictionary<string, string>(dictionary.OrderBy(x => x.Value));
Unlike a plain Dictionary, it also lets us read a pair by position, so orderedByValue.GetAt(1) returns [3, banana].
Conclusion
In this article, we’ve learned some of the different ways to sort a dictionary by value in C#. From the benchmark, we found that the three methods are close in speed, so we pick OrderBy() because it is the simplest to write. We also saw how to sort by key, and where SortedDictionary and OrderedDictionary fit when the order has to stay. If you’d like to learn more about sorting objects in lists, check out our article Sort List by Property in the Object in .NET.
Tested with .NET 10.0.10, BenchmarkDotNet 0.15.8 and xUnit 2.9.3.

The SortDictionaryValueUsingLinqQueryExpression would literally be translated by the compiler into:
That last
Select()does nothing except add the little bit of overhead we see. I make a point of only using the query syntax when I’m using theselectto project the data into a different object.Thank you James for this info.