Sorting HashMap based on keys in C#

王林
Release: 2023-09-10 20:45:10
forward
1160 people have browsed it

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);
Copy after login

Now get the keys and sort them using ToList() and Sort() methods respectively.

// get keys
var val = d.Keys.ToList();

// sort
val.Sort();
Copy after login

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);
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template