c# dictionary查找算法
时间: 2023-08-02 09:39:03 浏览: 117
C#中的`Dictionary`是基于哈希表实现的数据结构,因此查找操作的时间复杂度为O(1)。下面是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("orange", 3);
if (dict.ContainsKey("apple"))
{
int value = dict["apple"];
Console.WriteLine($"The value of 'apple' is {value}");
}
else
{
Console.WriteLine("The key 'apple' does not exist in the dictionary");
}
if (dict.ContainsKey("pear"))
{
int value = dict["pear"];
Console.WriteLine($"The value of 'pear' is {value}");
}
else
{
Console.WriteLine("The key 'pear' does not exist in the dictionary");
}
}
}
```
输出结果为:
```
The value of 'apple' is 1
The key 'pear' does not exist in the dictionary
```
可以看到,通过`Dictionary`的`ContainsKey`方法和索引访问,可以快速判断一个键值是否存在,并获取对应的值。
阅读全文