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 遍历键值对");
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}
// 方法二:使用 foreach 分别遍历键和值
Console.WriteLine("\n方法二:使用 foreach 分别遍历键和值");
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 循环和索引器(不推荐)");
var keys = new List<string>(dictionary.Keys);
for (int i = 0; i < keys.Count; i++)
{
Console.WriteLine($"Key = {keys[i]}, Value = {dictionary[keys[i]]}");
}
}
}
Dictionary<string, int>
类型的字典对象,并初始化一些键值对。foreach
遍历 KeyValuePair<string, int>
,可以直接访问每个键值对的键和值。dictionary.Keys
获取所有键,通过 dictionary.Values
获取所有值。以上代码展示了三种不同的遍历 Dictionary
的方法,其中前两种是最常用和推荐的方式。
上一篇:c# post请求
下一篇:c# out ref
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站