This post will discuss how to check whether a specific value already exists in a Dictionary<TKey,TValue> in C#.

1. Using Dictionary<TKey,TValue>.ContainsValue() method

The Dictionary<TKey,TValue> class contains the ContainsValue() method, which checks if it contains a specific value or not. It returns a boolean value to indicate the value is found or not.

Download  Run Code

 
Alternatively, you can use the ContainsKey() method to check if a Dictionary<TKey,TValue> contains a specific key.

Download  Run Code

2. Using Enumerable.Any() method

The Any() method returns true if any element of the sequence satisfies the provided condition. To check whether a value exists in a dictionary, you can use it like below. Note that you need to include the System.Linq namespace.

Download  Run Code

3. Using Custom Routine

The more traditional approach to finding a value in a dictionary involves iterating through the dictionary and checking each key-value pair for the matching value. In C#, this translates to:

Download  Run Code

 
The above solution iterates over the dictionary mappings using the foreach loop. You can directly iterate over all the values contained in the dictionary using the Dictionary<TKey,TValue>.Values property.

Download  Run Code

That’s all about checking whether a specific value already exists in a Dictionary<TKey,TValue> in C#.