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;
- }
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");
- }
Here is the complete sample code showing how to use these methods.
- // Create a dictionary with string key and Int16 value pair
- 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);
- // Count
- Console.WriteLine("Count: {0}", AuthorList.Count);
- // Set Item value
- AuthorList["Neel Beniwal"] = 9;
- if (!AuthorList.ContainsKey("Mahesh Chand"))
- {
- AuthorList["Mahesh Chand"] = 20;
- }
- if (!AuthorList.ContainsValue(9))
- {
- Console.WriteLine("Item found");
- }
- // Read all items
- Console.WriteLine("Authors all items:");
- foreach (KeyValuePair<string, Int16> author in AuthorList)
- {
- Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
- }

kartiikeya bakePosted May 29, 2015, 2:54 AM
Instead of checking every single key , how to check multiple keys are available or not ? with a small code...please help
Sam HobbsPosted Jun 30, 2012, 5:13 PM
Also the TryGetValue is good for determining if a key exists and if it does then it gets the value. Also the Item Property gets the value for a key but it throws an exception if the key does not exist. The Item Property can be used using the syntax Dictionay[key]. In other words, AuthorList["Neel Beniwal"] could be used to get the value but it will throw an exception if the key does not exist.