How to iterate any Map in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 31-Aug-2018 08:10:54
Advertisements