How to Sort a Dictionary by Key in .NET/C#

How to Sort a Dictionary by Key in C#, dotnet,csharp,sort dictionary using c#, c# sort dictionary, c# sorted dictionary, order dictionary using c#, c# order dictionary, c# ordered dictionary, Easy Way to Sort a Dictionary by Key in C#

In this post, we are going to explore different ways to make a C# sorted dictionary. But first, let's review the dictionary characteristics and then learn how to get this dictionary sorted by key.

C# - Dictionary<TKey, TValue>

In C#, the Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no particular order.

Here are the main characteristics of the Dictionary in C#

  • Dictionary<TKey, TValue> stores key-value pairs.
  • Comes under System.Collections.Generic namespace.
  • Implements IDictionary<TKey, TValue> interface.
  • Keys must be unique and cannot be null.
  • Values can be null or duplicate.
  • Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
  • Elements are stored as KeyValuePair<TKey, TValue> objects.

Sorting a dictionary with .NET/C#

In this section, we will learn few easy ways in C# to sort a .NET dictionary by key. Let's assume we have the following dictionary, the key represents the country name and the value is just an integer:

var dictionary = new Dictionary<string, int>();
dictionary.Add("Netherlands", 287);
dictionary.Add("France", 544);
dictionary.Add("USA", 765);
dictionary.Add("Germany", 436);
dictionary.Add("Belgium", 242);

Option #1: Use OrderBy to Sort C# Dictionary

To sort a C# Dictionary by it's keys, use OrderBy or OrderByDescending

var l = r.OrderBy(key => key.Key);
var dic = l.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);

foreach (var item in dic)
{
    Console.WriteLine(item.Key);
}

Option #2: Use C# SortedDictionary

C# Sorted Dictionary represents a collection of key/value pairs that are sorted by the key. It allows us to avoid sorting the keys on our own. However, Its lookup performance is slower than the regular Dictionary. The following code example creates an empty SortedDictionary<TKey,TValue> of integers with string keys and uses the Add method to add some elements. The example demonstrates how the items in the dictionary are sorted automatically.

var sorted = new SortedDictionary<string, int>();
// Add some elements to the dictionary.
sorted.Add("zebra", 5);
sorted.Add("cat", 2);
sorted.Add("dog", 9);
sorted.Add("mouse", 4);
sorted.Add("bird", 7);
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
foreach( KeyValuePair<string, int> kvp in sorted)
{
   Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

/* This code example produces the following output:
Key = bird, Value = 7
Key = cat, Value = 2
Key = dog, Value = 9
Key = mouse, Value = 4
Key = zebra, Value = 5

Post a Comment

Previous Post Next Post