Dictionary常规使用
C# 中的 Dictionary<TKey, TValue> 是一个非常实用的集合类型,用于存储键值对数据,并能通过键快速地查找、添加和删除值。以下是 Dictionary<TKey, TValue> 的基本用法和一些高级功能的代码描述。
初始化字典
// 初始化一个空的字典
Dictionary<int, string> dictionary = new Dictionary<int, string>();
// 初始化带有一些键值对的字典
Dictionary<int, string> initializedDictionary = new Dictionary<int, string>()
{
{1, "one"},
{2, "two"},
{3, "three"}
};
添加键值对
dictionary.Add(1, "one"); // 添加单个键值对
// 如果键不存在则添加,如果存在则不添加也不修改
if (!dictionary.ContainsKey(4))
{
dictionary.Add(4, "four");
}
// 尝试添加键值对,如果键已存在则不会抛出异常
bool success = dictionary.TryAdd(5, "five"); // 注意:TryAdd 方法实际上并不存在于 Dictionary 类型中,但可以使用ContainsKey方法达到类似的效果
if (!success)
{
Console.WriteLine("The key already exists.");
}
// 但实际使用中,可以这样模拟 TryAdd 的行为:
if (!dictionary.ContainsKey(5))
{
dictionary[5] = "five"; // 如果键不存在则添加,否则替换值(但此处我们希望仅在键不存在时添加)
}
else
{
// 处理键已存在的情况
}
注意:Dictionary 并没有直接提供 TryAdd 方法。如果你需要一个这样的功能,并且正在使用 .NET Framework 4.5 或更高版本,你可以考虑使用 ConcurrentDictionary,它提供了 TryAdd 方法用于线程安全的添加操作。
访问键值对
string value = dictionary[1]; // 通过键访问值,如果键不存在将抛出异常
string valueOrDefault = dictionary.TryGetValue(6, out string outValue) ? outValue : "default"; // 尝试获取值,如果键不存在则返回默认值而不抛出异常
// 遍历字典中的所有键值对
foreach (KeyValuePair<int, string> kvp in dictionary)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
// 使用 LINQ 查询特定的键值对
var filtered = dictionary.Where(kvp => kvp.Value.StartsWith("t")); // 查询所有值以 "t" 开头的键值对
foreach (var kvp in filtered)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
更改值
// 通过键更改值,如果键不存在将抛出异常
dictionary[2] = "two updated";
// 安全地更改值,只有在键存在时才更改
if (dictionary.ContainsKey(3))
{
dictionary[3] = "three updated";
}
删除键值对
dictionary.Remove(1); // 通过键删除键值对,如果键不存在将抛出异常(实际上如果键不存在并不会抛出异常,但返回值表示是否成功删除)
bool removed = dictionary.Remove(4); // 尝试删除键值对,并检查是否成功删除
// 清空字典中的所有键值对
dictionary.Clear();
检查键或值是否存在
bool containsKey = dictionary.ContainsKey(2); // 检查键是否存在
bool containsValue = dictionary.ContainsValue("one updated"); // 检查值是否存在(线性搜索,性能较差)
字典中的其他方法
// 获取字典中的键集合
ICollection<int> keys = dictionary.Keys;
// 获取字典中的值集合
ICollection<string> values = dictionary.Values;
// 获取字典中的键值对数量
int count = dictionary.Count;
// 判断字典是否为空(不含有任何键值对)
bool isEmpty = dictionary.Count == 0;
这些是使用 Dictionary<TKey, TValue> 的基础操作和一些高级特性的示例代码。Dictionary 提供了高效的数据检索机制,特别是在需要按照键快速查找数据时。但是,需要注意的是 Dictionary 并非线程安全,如果在多线程环境中使用,应当进行适当的同步以避免并发问题。对于线程安全的替代方案,可以考虑使用 ConcurrentDictionary<TKey, TValue> 。