HashMap is a Java language, not a C# language. HashMap in C# is equivalent to Dictionary and is used as a collection of key-value pairs.
First, set up 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() methods respectively.
// get keys var val = d.Keys.ToList(); // sort val.Sort();
Here is the complete example of sorting a HashMap based on keys -
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); } } }
The above is the detailed content of Sorting HashMap based on keys in C#. For more information, please follow other related articles on the PHP Chinese website!