C# Dictionary get key from value

Here is a simple thing missing from the Dictionary class.

When you have a Dictionary:

Dictionary<string, object> SampleDict;

Getting the value by specifying a key is straight forward:

object obj = SampleDict[“someKey”];

But how do you get the key by specifying a value?
There is no such thing in the Dictionary class!
What you’ll usually do is loop the Dictionary to find the value and return its relevant key.
I have made it into an extension class so it can be used like any other Dictionary member:

using System;
using System.Collections.Generic;

namespace Utils
{
    public static class IDictionaryExtensions
    {
        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");
        }
    }
}

And you use it like so:

String result = SampleDict.FindKeyByValue(someObject);

As you can see any type can be used with the Dictionary: IDictionary<TKey, TValue>

Follow

Get every new post delivered to your Inbox.