How to find a value in a Dictionary with C#

Find a Key

The ContainsKey method checks if a key is already exists in the dictionary. The following code snippet checks if a key is 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.

// Create a dictionary with string key and Int16 value pair

Dictionary<stringInt16> AuthorList = new Dictionary<stringInt16>();
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<stringInt16> author in AuthorList)
{
    Console.WriteLine("Key: {0}, Value: {1}"author.Key, author.Value);
}


Up Next
    Ebook Download
    View all
    Learn
    View all