using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个 Dictionary,键为字符串类型,值为整数类型
Dictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "apple", 1 },
{ "banana", 2 },
{ "cherry", 3 }
};
// 方法一:使用 foreach 遍历键值对
Console.WriteLine("方法一:遍历键值对");
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}
// 方法二:使用 foreach 分别遍历键和值
Console.WriteLine("\n方法二:分别遍历键和值");
foreach (string key in dictionary.Keys)
{
Console.WriteLine($"Key = {key}, Value = {dictionary[key]}");
}
foreach (int value in dictionary.Values)
{
Console.WriteLine($"Value = {value}");
}
// 方法三:使用 for 循环和索引器(不推荐,因为 Dictionary 不支持直接索引访问)
Console.WriteLine("\n方法三:使用 for 循环(不推荐)");
int index = 0;
var keys = new List<string>(dictionary.Keys);
for (index = 0; index < dictionary.Count; index++)
{
string key = keys[index];
Console.WriteLine($"Key = {key}, Value = {dictionary[key]}");
}
}
}
创建 Dictionary:
Dictionary<string, int> 创建一个字典对象,并初始化一些键值对。方法一:使用 foreach 遍历键值对:
foreach 遍历 KeyValuePair<string, int> 类型的元素,可以直接获取每个键值对的键和值。方法二:使用 foreach 分别遍历键和值:
dictionary.Keys 获取所有键,通过 dictionary.Values 获取所有值。方法三:使用 for 循环和索引器(不推荐):
希望这些代码和解释能帮助你理解如何遍历 C# 中的 Dictionary。
上一篇:c#枚举类型enum用法
下一篇:c# restsharp
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站