Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

how does containsKey differ from containsValue ?

public Dictionary<string, string> dictionary = new Dictionary<string, string>();


if(dictionary.ContainsValue("123"))
{

}
if(dictionary.ContainsKey("123"))
{

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
662 views
Welcome To Ask or Share your Answers For Others

1 Answer

Dictionarys are mappings from a key to a value.

ContainsKey() checks if your dictionary contains a certain key, it is very fast - looking up keys (and finding the data associated with that key) is the main strength of dictionaries. You might need this, to avoid accessing a non-existent Key - read about TryGetValue() in that case - it might be a better choice to avoid accessing non existing keys data.

ContainsValue() iterates over all values and checks if it is in the dictionary, it is a slow and cumbersome procedure because it needs to go to all values until the first one matches. Accessing values not by its key, but by iterating all is not what dictionaries are about.

Doing a ContainsKey() is fine, if you feel you need to do a ContainsValue() you are probably operating on the wrong kind of data structure.

Doku:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...