如何迭代 C# 中的任何 Map
C# 没有内置的 Math 类型。对于相同的类型,请使用 Dictionary。
首先,创建一个 Dictionary −
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("keyboard", 1);
d.Add("mouse", 2);获取键 −
var val = d.Keys.ToList();
现在,使用 foreach 循环迭代 Map −
foreach (var key in val) {
Console.WriteLine(key);
}为了迭代它,尝试运行以下代码 −
示例
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);
}
}
}输出
keyboard mouse
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP