DEV Community

Deependra kushwah
Deependra kushwah

Posted on

How to Sort C# Dictionary?

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

    }
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)