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. 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}", author.Key, author.Value);
  25. }