简体   繁体   English

字典中用于检查键是否存在的逻辑

[英]Logic used in dictionary to check existence of key

Dictionary cannot have two values with same key. 字典不能有两个具有相同键的值。 please tell which logic/algorithm being used in determining whether the key exists or not. 请说明在确定密钥是否存在时使用哪种逻辑/算法。

埃里克·利珀特(Eric Lippert)在他的博客文章中详尽地解释了这一点。

How about method ContainsKey of Dictionary? 字典的方法ContainsKey怎么样?

There are many ways to check for the key but I think this method is most graceful. 有很多方法可以检查密钥,但是我认为这种方法最合适。

Simple put it in try catch 简单放入尝试

if key exist will remain in try, else if not exists will come in catch 如果密钥存在,将继续尝试,否则将捕获

Dictionary<string, int> dic = new Dictionary<string, int>();

string str = "";
try
{
   int a = dic["keytofind"];
   str = "Key Found";
}
catch(Exception)
{
   str = "Key Not Found";
}

Trie data structure is used to store the keys. Trie数据结构用于存储密钥。 positive points of using this data structure : 1. Saving of storage space. 使用此数据结构的积极点:1.节省存储空间。 2. In O(Log(n)+constant) complexity can be determined about the existence of key. 2.在O(Log(n)+ constant)中,可以确定密钥存在的复杂性。

More details about trie data structure can be found here 关于特里数据结构的更多细节可以在这里找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM