Home  >  Article  >  Backend Development  >  How to iterate over any Map in C#

How to iterate over any Map in C#

WBOY
WBOYforward
2023-09-08 16:57:021881browse

如何在 C# 中迭代​​任何 Map

#C# has no built-in math types. Again, use a dictionary.

First, create a dictionary -

Dictionary<string, int> d = new Dictionary<string, int>();

d.Add("keyboard", 1);
d.Add("mouse", 2);

Get the key -

var val = d.Keys.ToList();

Now, use a foreach loop to iterate over the Map -

foreach (var key in val) {
   Console.WriteLine(key);
}

To iterate over it, try Run the following code -

Example

Live Demonstration

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      Dictionary<string, int> d = new Dictionary<string, int>();

      d.Add("keyboard", 1);
      d.Add("mouse", 2);

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

      // sort
      val.Sort();

      // displaying sorted keys
      foreach (var key in val) {
         Console.WriteLine(key);
      }
   }
}

Output

keyboard
mouse

The above is the detailed content of How to iterate over any Map 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