Skip to content

Instantly share code, notes, and snippets.

@javafun
Created June 26, 2014 04:39
Show Gist options
  • Save javafun/38e18a79b8482d75abc3 to your computer and use it in GitHub Desktop.
Save javafun/38e18a79b8482d75abc3 to your computer and use it in GitHub Desktop.
Find dictionary key by value
public static class IDictionaryExtensions
{
/// <summary>
/// Get key by value from dictionary
/// </summary>
/// <remarks>
/// Thanks for shemesh's neat solution
/// http://shemesh.wordpress.com/2010/01/22/c-dictionary-get-key-from-value/
/// </remarks>
public static TKey FindKeyByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
if (value.Equals(pair.Value)) return pair.Key;
throw new Exception("the value is not found in the dictionary");
}
/// <summary>
/// Get key by value from dictionary
/// </summary>
/// <remarks>
/// Extend the FindKeyByValue implementation and provide similar pattern to Dictionary TryGetValue method.
/// </remarks>
public static bool TryFindKeyByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value, out TKey key)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
key = default(TKey);
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
if (value.Equals(pair.Value))
{
key = pair.Key;
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment