This is pretty trivial using LINQ:
int key = new Dictionary<int,string>().Where((kv)=>kv.Value == "SomeValue").Select(kv=>kv.Key).FirstOrDefault();
And an extension method if you fancy:
static class DictionaryExtensions {
public static bool TryFindByValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TValue value, out TKey key) {
var keys = dict.Where((kv) => kv.Value.Equals(value)).Select(kv => kv.Key);
bool retValue = keys.Any();
key = keys.FirstOrDefault();
return retValue;
}
}
What you can also do is to implement IDictionary
, delegate to two Dictionary
objects (one for key-value mapping and one for value-key mapping) for backing store and have a constraint on Add
that values must be unique. That way you are guaranteed that there would be at most one entry with a particular value. EDIT Using two dictionaries will improve access time(Thanks @SamStephens) as both keys and values will be stored in an ordered hashtable.