在 C# 中,可以通过以下方法判断 Dictionary<TKey, TValue> 中是否存在特定的键:
1. 使用 ContainsKey 方法
ContainsKey 是判断键是否存在的最常用方法。如果字典包含指定的键,返回 true;否则返回 false。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{ 1, "Apple" },
{ 2, "Banana" }
};
// 判断是否存在键 1
if (myDictionary.ContainsKey(1))
{
Console.WriteLine("Key 1 exists in the dictionary.");
}
else
{
Console.WriteLine("Key 1 does not exist.");
}
}
}
2. 使用 TryGetValue 方法
TryGetValue 方法在检查键是否存在的同时,还可以获取对应的值。它返回一个布尔值:true 表示键存在并获取到值,false 表示键不存在。
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{ 1, "Apple" },
{ 2, "Banana" }
};
// 使用 TryGetValue 检查键并获取值
if (myDictionary.TryGetValue(1, out string value))
{
Console.WriteLine($"Key 1 exists with value: {value}");
}
else
{
Console.WriteLine("Key 1 does not exist.");
}
3. 直接检查索引器访问
通过索引器 ([]) 访问时,若键不存在会抛出 KeyNotFoundException。因此,不推荐直接用索引器来判断键是否存在,但可以捕获异常。
try
{
string value = myDictionary[1];
Console.WriteLine($"Key 1 exists with value: {value}");
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key 1 does not exist.");
}
对比和建议
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
ContainsKey | 简洁直观,效率高。 | 只判断键是否存在,不获取值。 | 只需要判断键是否存在时。 |
TryGetValue | 判断键存在的同时获取值,避免再次查找。 | 比 ContainsKey 稍复杂。 | 需要获取值且需要判断键是否存在时。 |
| 索引器 + 异常 | 代码简单,直接获取值。 | 性能低,抛出异常代价较高。 | 应尽量避免,仅作为补充方式。 |
最佳实践
在判断字典是否包含键时,优先使用 ContainsKey 或 TryGetValue。如果同时需要判断键是否存在并获取值,使用 TryGetValue 是最优选择。
923

被折叠的 条评论
为什么被折叠?



