How to find a key 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, adds it.

  1. if (!AuthorList.ContainsKey("Mahesh Chand"))  
  2. {  
  3.     AuthorList["Mahesh Chand"] = 20;  
  4. }
Find a Value
 
The ContainsValue method checks if a value already exists in the dictionary. The following code snippet checks if a value already exits.
  1. if (!AuthorList.ContainsValue(9))  
  2. {  
  3.     Console.WriteLine("Item found");  

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


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.