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 和 Values 属性遍历值
Console.WriteLine("\n遍历方法三:使用 foreach 和 Values 属性遍历值");
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 对象。KeyValuePair 包含键和值的组合,可以直接访问 Key 和 Value 属性。foreach 分别遍历键和值。通过 Keys 属性获取所有键,然后通过键访问对应的值。Values 属性直接遍历所有的值。for 循环和索引器遍历。这种方法不推荐,因为 Dictionary 不保证键值对的顺序。以上代码展示了多种遍历 Dictionary 的方法,可以根据实际需求选择合适的方式。
上一篇:c# list orderby
下一篇:c# byte[]转string
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站