在C#中,Dictionary<TKey, TValue> 是一个泛型集合类,属于 System.Collections.Generic 命名空间。它存储了键值对(key-value pairs),允许你使用唯一的键来快速检索、添加、修改和删除元素。
以下是C#中Dictionary<TKey, TValue>的一些基本操作:
初始化:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
添加元素 - 使用 Add 方法将键值对添加到字典中:
dictionary.Add("key1", 1);
尝试添加元素 - 使用 TryAdd 方法在键不存在时添加键值对:
bool added = dictionary.TryAdd("key2", 2);
访问元素 - 使用索引器通过键访问或设置值:
int value = dictionary["key1"];
dictionary["key1"] = 10; // 更新值
移除元素 - 使用 Remove 方法根据键移除键值对:
bool removed = dictionary.Remove("key1");
检查键是否存在 - 使用 ContainsKey 方法检查字典是否包含特定键:
bool containsKey = dictionary.ContainsKey("key1");
获取键的集合 - 使用 Keys 属性获取字典中所有键的集合:
IEnumerable<string> keys = dictionary.Keys;
获取值的集合 - 使用 Values 属性获取字典中所有值的集合:
IEnumerable<int> values = dictionary.Values;
获取字典中键值对的数量 - 使用 Count 属性:
int count = dictionary.Count;
清空字典 - 使用 Clear 方法:
dictionary.Clear();
遍历字典 - 使用 foreach 循环遍历字典中的所有键值对:
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
查找具有特定键的值 - 使用 this 索引器或 TryGetValue 方法:
int value;
bool found = dictionary.TryGetValue("key2", out value);
下面是一个简单的C# Dictionary<TKey, TValue> 使用示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>
{
{"key1", 1},
{"key2", 2}
};
// 添加元素
dictionary.Add("key3", 3);
// 尝试添加元素
bool added = dictionary.TryAdd("key4", 4);
// 访问元素
int value1 = dictionary["key1"];
dictionary["key1"] = 10; // 更新值
// 移除元素
bool removed = dictionary.Remove("key3");
// 检查键是否存在
bool containsKey = dictionary.ContainsKey("key1");
// 获取键的集合
IEnumerable<string> keys = dictionary.Keys;
// 获取值的集合
IEnumerable<int> values = dictionary.Values;
// 打印键和值
foreach (KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
// 获取字典中键值对的数量
int count = dictionary.Count;
// 清空字典
dictionary.Clear();
Console.WriteLine("Count after clearing: " + dictionary.Count);
}
}
想了解更多游戏开发知识,可以扫描下方二维码,免费领取游戏开发4天训练营课程