tags:

views:

158

answers:

4

How do I get a Dictionary key by value in C#?

Dictionary<string, string> types = new Dictionary<string, string>()
{
            {"1", "one"},
            {"2", "two"},
            {"3", "three"}
};

I want something like this:

getByValueKey(string value);

getByValueKey("one") must be return "1".

What is the best way do this? Maybe HashTable, SortedLists?

+3  A: 

You could do that:

  1. By looping through all the KeyValuePair<TKey, TValue>'s in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary)
  2. Use two dictionaries, one for value-to-key mapping and one for key-to-value mapping (which would take up twice as much space in memory).

Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.

Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.

Is there any reason you can't reverse the key-value relationship?

Zach Johnson
thanks, for ideas.
loviji
+1  A: 

What if the value exists for more than one key?

Which key should be returned?

To avoid making assumptions Microsoft hasn't included a GetKey method.

Ben S
+3  A: 

Values not necessarily have to be unique so you have to do a lookup: something like this types.Where(x => x.Value == "one").FirstOrDefault();

if values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.

Al Bundy
my values are not dublicated. so your idea is good for me. thanks.
loviji
@loviji: Keep in mind that in the looping solution, if the value happens to be at the end of the dictionary, it will have to go over all the other values to find it. If you have a number of entries, this will slow your program down.
Zach Johnson
@Zach Johnson: Thanks. i agree with you. and your answer i like too. but in my dictionary 8-10 entries. and they aren't added dynamically. and i think, using this answer not bad solution.
loviji
A: 

I don't exactly get what you want to accomplish, and perhaps are you obliged to store the number string as the key or is this what you are stuck with.

However, making the KeyValuePair store this way by inverting both values:

Dictionary<string, string> stringDictionary = new Dictionary<string, string>();
stringDictionary.Add("one", "1");
stringDictionary.Add("two", "2");

Then, retrieving the desired value like so:`

Console.WriteLine(stringDictionary("one")); // This line will print 1 as a string on screen.
Console.ReadLine();

Is this what you want, or am I mistaken?

Will Marcouiller