4

It seems like a pretty straightforward thing to add, but I just want to be sure .NET doesn't already provide one and save me from adding unnecessary code:

I need a lookup table (like a Dictionary) that instead using a key/value pair, uses the first key to find the second key, and vice versa. For example -

theList.Add("foo", "bar");
x = theList["foo"]; // Returns "bar"
y = theList["bar"]; // Returns "foo"

Thanks in advance!

svick
  • 10,137
  • 1
  • 39
  • 53

2 Answers2

9

There is no such datatype, probably because this is a very special requirement which can be easily solved by utilizing a dictionary and adding simply both pairs

 theDictionary.Add("foo", "bar");
 theDictionary.Add("bar", "foo");

Obviously, you can put this into a generic function like

void MyDictAdd(Dictionary<T,T> dict, T key1, T key2)
{
    dict.Add(key1,key2);
    dict.Add(key2,key1);
}
Doc Brown
  • 218,378
0

Another possibility would be to create a method which would search both keys and values. Also this would and more complexity to the mix O(n) for the search. But would reduce memory usage.

string GetValue(string search, Dictionary<string, string> dictionary) {
    foreach(var pair in dictionary)
    {
        if (pair.Key == search) {
            return pair.Value;
        }
        else if (pair.Value == search) {
            return pair.Key;
        }
    }
    return null;
}
fsacer
  • 111