Home  >  Article  >  Backend Development  >  Sorting HashMap based on keys in C#

Sorting HashMap based on keys in C#

王林
王林forward
2023-09-10 20:45:101161browse

C# 中根据键对 HashMap 进行排序

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 -

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete