using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个字典,键为字符串类型,值为整数类型
Dictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "apple", 1 },
{ "banana", 2 },
{ "cherry", 3 }
};
// 方法1:使用 foreach 遍历字典的键值对
Console.WriteLine("遍历方法1:使用 foreach 遍历键值对");
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}
// 方法2:使用 foreach 分别遍历键和值
Console.WriteLine("\n遍历方法2:分别遍历键和值");
foreach (string key in dictionary.Keys)
{
Console.WriteLine($"Key = {key}, Value = {dictionary[key]}");
}
foreach (int value in dictionary.Values)
{
Console.WriteLine($"Value = {value}");
}
// 方法3:使用 for 循环和索引器(不推荐,因为 Dictionary 不支持索引访问)
// 注意:Dictionary 不支持直接通过索引访问元素,因此这种方法不可行。
// 仅作参考,不建议使用。
/*
for (int i = 0; i < dictionary.Count; i++)
{
Console.WriteLine($"Key = {dictionary.Keys[i]}, Value = {dictionary.Values[i]}");
}
*/
}
}
Dictionary<string, int>
类型的字典,并初始化了一些键值对。foreach
遍历键值对:这是最常用的方法,通过 KeyValuePair<TKey, TValue>
来访问每个键值对。for
循环和索引器:由于 Dictionary
不支持通过索引访问元素,这种方法是不可行的,仅供了解。如果你需要更多帮助或有其他问题,请告诉我!
下一篇:c# api
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站