Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting a HashMap according to keys in C#
In C#, the equivalent of Java's HashMap is the Dictionary class, which stores key-value pairs. Sorting a Dictionary by keys requires extracting the keys, sorting them, and then accessing the values in the sorted order.
Syntax
Following is the syntax for creating and sorting a Dictionary by keys −
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(); // Sort keys using LINQ var sortedByKeys = dict.OrderBy(x => x.Key); // Or extract and sort keys manually var keys = dict.Keys.ToList(); keys.Sort();
Using LINQ OrderBy Method
The most efficient way to sort a Dictionary by keys is using LINQ's OrderBy method, which returns the key-value pairs in sorted order −
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
Dictionary<string, int> sports = new Dictionary<string, int>();
sports.Add("soccer", 1);
sports.Add("cricket", 2);
sports.Add("tennis", 3);
sports.Add("rugby", 4);
sports.Add("basketball", 5);
Console.WriteLine("Original Dictionary:");
foreach (var item in sports) {
Console.WriteLine($"{item.Key}: {item.Value}");
}
Console.WriteLine("\nSorted by Keys:");
var sortedDict = sports.OrderBy(x => x.Key);
foreach (var item in sortedDict) {
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}
The output of the above code is −
Original Dictionary: soccer: 1 cricket: 2 tennis: 3 rugby: 4 basketball: 5 Sorted by Keys: basketball: 5 cricket: 2 rugby: 4 soccer: 1 tennis: 3
Using Manual Key Sorting
You can also extract the keys, sort them manually, and then iterate through the sorted keys to access Dictionary values −
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
Dictionary<string, int> sports = new Dictionary<string, int>();
sports.Add("soccer", 1);
sports.Add("cricket", 2);
sports.Add("tennis", 3);
sports.Add("rugby", 4);
// Get keys and sort them
var keys = sports.Keys.ToList();
keys.Sort();
Console.WriteLine("Dictionary sorted by keys:");
foreach (var key in keys) {
Console.WriteLine($"{key}: {sports[key]}");
}
}
}
The output of the above code is −
Dictionary sorted by keys: cricket: 2 rugby: 4 soccer: 1 tennis: 3
Sorting by Keys in Descending Order
To sort keys in descending order, use OrderByDescending method −
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
Dictionary<int, string> numbers = new Dictionary<int, string>();
numbers.Add(3, "Three");
numbers.Add(1, "One");
numbers.Add(4, "Four");
numbers.Add(2, "Two");
Console.WriteLine("Sorted by Keys (Descending):");
var sortedDesc = numbers.OrderByDescending(x => x.Key);
foreach (var item in sortedDesc) {
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}
The output of the above code is −
Sorted by Keys (Descending): 4: Four 3: Three 2: Two 1: One
Comparison of Sorting Methods
| Method | Advantages | Use Case |
|---|---|---|
| LINQ OrderBy | Concise, preserves key-value pairs, supports chaining | When you need both keys and values in sorted order |
| Manual Key Sorting | More control, can reuse sorted key list | When you only need sorted keys or custom sorting logic |
| SortedDictionary | Maintains sorted order automatically | When frequent insertions need to maintain sort order |
Conclusion
Sorting a Dictionary by keys in C# can be accomplished using LINQ's OrderBy method for a clean approach, or by manually extracting and sorting keys. The LINQ approach is preferred as it maintains the key-value relationship and provides cleaner, more readable code.
