c#dictionary通过key找value
时间: 2023-04-26 11:01:34 浏览: 1300
C# 中的 Dictionary 类有一个 TryGetValue 方法,可以通过 key 来查找 value。该方法接收两个参数,一个是 key,另一个是输出参数,用来保存找到的 value。如果找到了 value,TryGetValue 方法会返回 true,反之会返回 false。
示例:
```
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
int value;
if (dict.TryGetValue("apple", out value))
{
Console.WriteLine(value); // 输出: 1
}
```
也可以用下标来访问,如果key不存在会抛出异常
```
Console.WriteLine(dict["apple"]);
```
相关问题
c#字典怎么通过value找key
在 C# 中,可以通过以下方式通过 value 找到 key:
```csharp
// 创建一个字典
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);
// 通过 value 找到 key
string key = null;
foreach (KeyValuePair<string, int> kvp in dict)
{
if (kvp.Value == 2)
{
key = kvp.Key;
break;
}
}
// 输出结果
if (key != null)
{
Console.WriteLine("Key: " + key);
}
else
{
Console.WriteLine("Value not found in dictionary.");
}
```
在上述代码中,我们首先创建了一个 `Dictionary<string, int>`,并将一些键值对添加到其中。然后,我们使用 `foreach` 循环遍历字典中的所有键值对,检查每个值是否与我们要查找的值相等。如果找到了相等的值,我们将相应的键存储在变量 `key` 中,并使用 `break` 退出循环。最后,我们输出找到的键或相应的错误消息。
c#字典高效通过value找key
在 C# 中,如果需要高效地通过 value 找到 key,可以考虑使用双向字典库( `BiDictionary`)或使用 `HashSet`,但这两种方法都需要使用第三方库。如果希望使用标准库来实现高效的查找,可以考虑将字典的键值对颠倒一下,即将原字典中的键作为值,将原字典中的值作为键,然后再通过新的字典来查找。
以下是通过颠倒键值对来高效查找的示例代码:
```csharp
// 创建一个字典
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);
// 颠倒键值对,创建新字典
Dictionary<int, string> reverseDict = new Dictionary<int, string>();
foreach (KeyValuePair<string, int> kvp in dict)
{
reverseDict.Add(kvp.Value, kvp.Key);
}
// 通过 value 找到 key
string key = null;
if (reverseDict.TryGetValue(2, out key))
{
Console.WriteLine("Key: " + key);
}
else
{
Console.WriteLine("Value not found in dictionary.");
}
```
在上述代码中,我们首先创建了一个 `Dictionary<string, int>`,并将一些键值对添加到其中。然后,我们使用 `foreach` 循环颠倒字典中的键值对,创建一个新的 `Dictionary<int, string>`。最后,我们使用 `TryGetValue` 方法在新字典中查找指定值对应的键,并输出找到的键或相应的错误消息。此方法的时间复杂度为 O(1),比上一个示例中的方法更高效。