How to search / check the dictionary value by key

I am trying to confirm if a particular dictionary key contains a value

eg.

does dict01 contains the phrase "testing" in the "tester" key

Right now I need to iterate over the dictionary with KeyPair, which I don't want to do, as it wastes performance

+6
source share
3 answers

You can use ContainsKey and string.Contains :

var key = "tester"; var val = "testing"; if(myDictionary.ContainsKey(key) && myDictionary[key].Contains(val)) { // "tester" key exists and contains "testing" value } 

You can also use TryGetValue :

 var key = "tester"; var val = "testing"; var dicVal = string.Empty; if(myDictionary.TryGetValue(key, out dicVal) && dicVal.contains(val)) { // "tester" key exists and contains "testing" value } 
+10
source

You can use the following method if you do not want to iterate through the dictionary twice

 string value; var result = dict01.TryGetValue("tester", out value) && value.Contains("testing"); 
+2
source
 if (myDict.ContainsKey("tester")) // Do something? 

MSDN Details

0
source

Source: https://habr.com/ru/post/921599/


All Articles