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.
if (!AuthorList.ContainsKey("Mahesh
Chand"))
{
AuthorList["Mahesh Chand"]
= 20;
}
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.
if (!AuthorList.ContainsValue(9))
{
Console.WriteLine("Item
found");
}
Sample
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);
}