get dictionary key by value

Possible Duplicate:
Getting key of value of a generic Dictionary?

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?


Values not necessarily have to be unique so you have to do a lookup. You can do something like this:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;

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


You could do that:

  • 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)
  • 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?


    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.

    链接地址: http://www.djcxy.com/p/30412.html

    上一篇: 有关实现命令行界面的建议

    下一篇: 按价值获得字典键