using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个字典(Map)
Dictionary<string, int> ageMap = new Dictionary<string, int>();
// 添加键值对
ageMap.Add("Alice", 30);
ageMap.Add("Bob", 25);
ageMap.Add("Charlie", 35);
// 访问字典中的值
Console.WriteLine("Alice 的年龄是: " + ageMap["Alice"]);
// 检查键是否存在
if (ageMap.ContainsKey("Bob"))
{
Console.WriteLine("Bob 的年龄是: " + ageMap["Bob"]);
}
// 遍历字典
foreach (var item in ageMap)
{
Console.WriteLine($"{item.Key} 的年龄是 {item.Value}");
}
// 修改字典中的值
ageMap["Alice"] = 31;
// 删除键值对
ageMap.Remove("Charlie");
// 打印修改后的字典
Console.WriteLine("修改后的字典:");
foreach (var item in ageMap)
{
Console.WriteLine($"{item.Key} 的年龄是 {item.Value}");
}
}
}
Dictionary<string, int> 创建一个名为 ageMap 的字典,其中键是字符串类型,值是整数类型。Add 方法向字典中添加键值对。ageMap["Alice"]。ContainsKey 方法检查字典中是否包含某个键。foreach 循环遍历字典中的所有键值对。Remove 方法从字典中删除指定的键值对。上一篇:c# 截取字符串
下一篇:c# dictionary 用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站