How to Sort C# Dictionary?
Deependra kushwah
Posted on January 4, 2023
We can Sort any kind of collection with the help of methods exposed by Linq library in C#. Order by can be used to sort the collection.
static class Program
{
static void Main(string[] args)
{
var dictionary = new Dictionary<string, int>()
{
{ "Deep", 32 },
{ "Saurabh", 30 },
{ "Rahul", 35 },
{ "Jitendra", 24 }
};
foreach (var keyValuePair in dictionary)
{
Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value);
}
//After sorting
Console.WriteLine("\nAfter sorting\n");
var sortedDictionary = dictionary.OrderBy(x => x.Value);
foreach (var keyValuePair in sortedDictionary)
{
Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value);
}
//After sorting
Console.WriteLine("\nAfter Sorting in Descending Order\n");
var sortedDictionaryInDescOrder = dictionary.OrderByDescending(x => x.Value);
foreach (var keyValuePair in sortedDictionaryInDescOrder)
{
Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value);
}
Console.ReadKey();
}
}
💖 💪 🙅 🚩
Deependra kushwah
Posted on January 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.