How to iterate any Map in C#


C# has no built-in Math type. For the same, use a Dictionary.

Firstly, create a Dictionary −

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

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

Get the keys −

var val = d.Keys.ToList();

Now, use the foreach loop to iterate over the Map −

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

To iterate it, try to run the following code −

Example

 Live Demo

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

Updated on: 22-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements