You can do this:
var dict = new Dictionary<TKey, TValue>() ...
TValue myValue = ...
var myKey = dict.First(pair => pair.Value == myValue).Key;
This might fail if the value is not found in the dictionary. To be a bit safer you can do this:
var myKey = dict.FirstOrDefault(pair => pair.Value == myValue).Key;
Here myKey
will take the default value of type TKey
(null
for strings or other classes, 0
for integers, etc.), so depending on your exact situation you may need to take some care in how you handle this case.
Also, it's important to realize that you could have many keys with the same value. To select all of the keys use this:
var myKeys = dict.Where(pair => pair.Value == myValue).Select(pair => pair.Key);
Or in query syntax:
var myKeys =
from pair in dict
where pair.Value == myValue
select pair.Key;