This post will discuss how to get the corresponding key from the specified value in the Dictionary in C#.

1. Using Enumerable.FirstOrDefault() method

We can use LINQ’s FirstOrDefault() method to return the first KeyValuePair<K,V> of the dictionary whose value matches with the specified value.

Download  Run Code

2. Using foreach loop

We can also iterate over the dictionary using a foreach loop and match Value of each KeyValuePair<K,V> pair with the given value. If any match is found, we return the corresponding Key. The following code example demonstrates this:

Download  Run Code

3. Inverse Dictionary

If all values in the dictionary are unique, we can create a reverse dictionary where values become keys and keys becomes values.

The following code example shows how to implement this. If any of the values in the dictionary are repeated, the code throws an ArgumentException.

Download  Run Code

That’s all about getting the corresponding key from a given value in Dictionary in C#.