Sorting a HashMap according to keys in C#

CsharpProgrammingServer Side Programming

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);
      }
   }
}
raja
Published on 20-Aug-2018 08:44:13
Advertisements