C# key value
时间: 2023-09-05 15:10:54 浏览: 51
C# 中的键值对数据结构常用的有 Dictionary<TKey, TValue> 和 SortedDictionary<TKey, TValue>。其中,Dictionary<TKey, TValue> 是基于哈希表实现的,可以快速地通过键获取值;SortedDictionary<TKey, TValue> 则是基于红黑树实现的,可以对键进行排序,但是在访问元素时比 Dictionary<TKey, TValue> 慢一些。使用这两个类需要先声明泛型类型,如:
```csharp
Dictionary<string, int> dict = new Dictionary<string, int>();
SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>();
```
其中,string 表示键的类型,int 表示值的类型。你可以通过 Add() 方法向字典中添加键值对,通过索引器或 TryGetValue() 方法获取值,通过 ContainsKey() 方法判断是否存在某个键,通过 Remove() 方法移除某个键值对等等。
相关问题
c#dictionary通过key找value
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# dictionary 通过value查找key值
在 C# 中,Dictionary 类提供了通过值查找键的方法。你可以使用 LINQ 查询语法或循环遍历字典来实现这个功能。以下是两种方法的示例:
1. 使用 LINQ 查询语法:
```csharp
var dictionary = new Dictionary<string, int>
{
{ "apple", 1 },
{ "banana", 2 },
{ "orange", 3 }
};
int targetValue = 2;
string key = dictionary.FirstOrDefault(x => x.Value == targetValue).Key;
if (key != null)
{
Console.WriteLine($"Key with value {targetValue} is: {key}");
}
else
{
Console.WriteLine("Key not found for the given value.");
}
```
2. 使用循环遍历字典:
```csharp
var dictionary = new Dictionary<string, int>
{
{ "apple", 1 },
{ "banana", 2 },
{ "orange", 3 }
};
int targetValue = 2;
string key = null;
foreach (var kvp in dictionary)
{
if (kvp.Value == targetValue)
{
key = kvp.Key;
break;
}
}
if (key != null)
{
Console.WriteLine($"Key with value {targetValue} is: {key}");
}
else
{
Console.WriteLine("Key not found for the given value.");
}
```
这些代码示例将在给定一个目标值时,通过值查找字典中对应的键。请注意,如果字典中存在多个具有相同值的键,这些方法将返回第一个匹配的键。