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.
- if (!AuthorList.ContainsKey("Mahesh Chand"))
- {
- AuthorList["Mahesh Chand"] = 20;
- }
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.
- if (!AuthorList.ContainsValue(9))
- {
- Console.WriteLine("Item found");
- }
Sample
Here is the complete sample code showing how to use these methods.
-
-
- Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
- AuthorList.Add("Mahesh Chand", 35);
- AuthorList.Add("Mike Gold", 25);
- AuthorList.Add("Praveen Kumar", 29);
- AuthorList.Add("Raj Beniwal", 21);
- AuthorList.Add("Dinesh Beniwal", 84);
-
-
-
- Console.WriteLine("Count: {0}", AuthorList.Count);
-
-
- AuthorList["Neel Beniwal"] = 9;
-
- if (!AuthorList.ContainsKey("Mahesh Chand"))
- {
- AuthorList["Mahesh Chand"] = 20;
- }
-
- if (!AuthorList.ContainsValue(9))
- {
- Console.WriteLine("Item found");
- }
-
-
-
- Console.WriteLine("Authors all items:");
-
- foreach (KeyValuePair<string, Int16> author in AuthorList)
- {
- Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
- }