DEV Community

Deependra kushwah
Deependra kushwah

Posted on

1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay