- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting a HashMap according to keys in C#
HashMap is in Java, not C#. The equivalent of HashMap in C# is Dictionary that is used as a collection of key-value pair.
Firstly, set the Dictionary −
Dictionary<string, int> d = new Dictionary<string, int>(); d.Add("soccer", 1); d.Add("cricket", 2); d.Add("tennis", 3); d.Add("rugby", 4);
Now get the keys and sort them using ToList() and Sort() method respectively.
// get keys var val = d.Keys.ToList(); // sort val.Sort();
The following is the complete example to sort a HashMap according to keys −
Example
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { Dictionary<string, int> d = new Dictionary<string, int>() d.Add("soccer", 1); d.Add("cricket", 2); d.Add("tennis", 3); d.Add("rugby", 4); // get keys var val = d.Keys.ToList(); // sort val.Sort(); // displaying sorted keys foreach (var key in val) { Console.WriteLine(key); } } }
Advertisements