using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个哈希表(字典)
Dictionary<string, int> hashTable = new Dictionary<string, int>();
// 添加键值对到哈希表
hashTable.Add("apple", 1);
hashTable.Add("banana", 2);
hashTable.Add("cherry", 3);
// 查找哈希表中的值
if (hashTable.ContainsKey("banana"))
{
Console.WriteLine("Value for 'banana': " + hashTable["banana"]);
}
// 遍历哈希表
foreach (var item in hashTable)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
// 修改哈希表中的值
hashTable["apple"] = 10;
// 删除哈希表中的键值对
hashTable.Remove("cherry");
// 输出修改后的哈希表内容
Console.WriteLine("After modifications:");
foreach (var item in hashTable)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
}
}
Dictionary<TKey, TValue> 类来创建哈希表,其中 TKey 是键的类型,TValue 是值的类型。在示例中,我们创建了一个 Dictionary<string, int>。Add 方法向哈希表中添加键值对。ContainsKey 方法检查哈希表中是否存在指定的键,并通过键获取对应的值。foreach 循环遍历哈希表中的所有键值对。Remove 方法从哈希表中移除指定的键值对。上一篇:c# string数组
下一篇:c# 反序列化
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站