How to find a value in a Dictionary with C#

Find a Key

The ContainsKey method checks if a key already exists in the dictionary. The following code snippet checks if a key already exits and if not, add one. 

  1. if (!AuthorList.ContainsKey("Mahesh Chand"))  
  2. {  
  3.     AuthorList["Mahesh Chand"] = 20;  
  4. }  
Find a Value 

The ContainsValue method checks if a value is already exists in the dictionary. The following code snippet checks if a value is already exits. 

  1. if (!AuthorList.ContainsValue(9))  
  2. {  
  3.     Console.WriteLine("Item found");  
  4. }   
Sample 

Here is the complete sample code showing how to use these methods.

  1. // Create a dictionary with string key and Int16 value pair  
  2.   
  3. Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
  4. AuthorList.Add("Mahesh Chand", 35);  
  5. AuthorList.Add("Mike Gold", 25);  
  6. AuthorList.Add("Praveen Kumar", 29);  
  7. AuthorList.Add("Raj Beniwal", 21);  
  8. AuthorList.Add("Dinesh Beniwal", 84);   
  9.   
  10. // Count  
  11.   
  12. Console.WriteLine("Count: {0}", AuthorList.Count);   
  13.   
  14. // Set Item value  
  15. AuthorList["Neel Beniwal"] = 9;  
  16.   
  17. if (!AuthorList.ContainsKey("Mahesh Chand"))  
  18. {  
  19.     AuthorList["Mahesh Chand"] = 20;  
  20. }  
  21.   
  22. if (!AuthorList.ContainsValue(9))  
  23. {  
  24.     Console.WriteLine("Item found");  
  25. }                      
  26.   
  27. // Read all items  
  28.   
  29. Console.WriteLine("Authors all items:");   
  30.   
  31. foreach (KeyValuePair<string, Int16> author in AuthorList)  
  32. {  
  33.     Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);  
  34. } 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.