It's easy to get the value of a key from a .Net 2.0 generic Dictionary:
Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2]; // Beta
But is there a simple way to get the key of a value?
int[] betaKeys = greek.WhatDoIPutHere("Beta"); // expecting single 2
As a twist of the accepted answer (https://stackoverflow.com/a/255638/986160) assuming that the keys will be associated with signle values in the dictionary. Similar to (https://stackoverflow.com/a/255630/986160) but a bit more elegant. The novelty is in that the consuming class can be used as an enumeration alternative (but for strings too) and that the dictionary implements IEnumerable.
And as a consuming class you could have
The "simple" bidirectional dictionary solution proposed here is complex and may be be difficult to understand, maintain or extend. Also the original question asked for "the key for a value", but clearly there could be multiple keys (I've since edited the question). The whole approach is rather suspicious.
Software changes. Writing code that is easy to maintain should be given priority other "clever" complex workarounds. The way to get keys back from values in a dictionary is to loop. A dictionary isn't designed to be bidirectional.
Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had
What would you expect to get for
greek.WhatDoIPutHere("Alpha")
?Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or
IEnumerable<T>
)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?Personally I'd go for an enumerable, like so:
revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys. that is, the values might not be unique
that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:
Use LINQ to do a reverse
Dictionary<K, V>
lookup. But keep in mind that the values in yourDictionary<K, V>
values may not be distinct.Demonstration:
Expected Output: