using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个字典,键为字符串类型,值为整数类型
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// 向字典中添加键值对
dictionary.Add("apple", 1);
dictionary.Add("banana", 2);
dictionary.Add("cherry", 3);
// 访问字典中的值
Console.WriteLine("The value for 'apple' is: " + dictionary["apple"]);
// 检查字典中是否包含某个键
if (dictionary.ContainsKey("banana"))
{
Console.WriteLine("The value for 'banana' is: " + dictionary["banana"]);
}
// 遍历字典
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
// 修改字典中的值
dictionary["apple"] = 10;
// 删除字典中的键值对
dictionary.Remove("cherry");
// 打印修改后的字典
foreach (var item in dictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
}
}
}
Dictionary<TKey, TValue> 类来创建字典,其中 TKey 是键的类型,TValue 是值的类型。在示例中,我们创建了一个键为字符串、值为整数的字典。Add 方法向字典中添加键值对。ContainsKey 方法检查字典中是否包含某个键。foreach 循环遍历字典中的所有键值对。Remove 方法删除字典中的键值对。上一篇:c#开发
下一篇:c#字符串截取
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站