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>

Advertisements

6 Responses to C# Dictionary get key from value

  1. xinyustudio says:

    This only returns the first key that matches the condition.

    var RelatedKeys=
    from KeyValuePair pair in dictionary)
    where(value.Equals(pair.Value)
    select pair.Key;

    will return all the related keys.

  2. shvilam says:

    a function like this – if you want to be coherent with the rest of the api – do not throw an exception

  3. ramesh says:

    Good article………

  4. Bey says:

    Shemesh – nice article.
    Suppose i don’t know the contents of the key(s) or the values, how do you get the first key or the first value in a dictionaly with a non-null key/value pair?

    Thanks, and keep shining,

    Bey

  5. Darkhog says:

    Cool and useful! I wonder why this isn’t in C# by default, there should be a way to do two-way lookup.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: