How to iterate over any Map in C#

WBOY
Release: 2023-09-08 16:57:02
forward
1855 people have browsed it

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

Get the key -

var val = d.Keys.ToList();
Copy after login

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

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

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

Output

keyboard
mouse
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!