28/10/11: minor edit for clarity, and to fix a missing CRLF in the code sample that made the List declaration part of a comment.
...
My sense is that SAK has definitively answered this question, but I will add a corollary: back when I was experimenting with such 'mirrored' dual dictionaries, I found myself questioning if the same task (lookup by key or value) could be just as efficiently done using generic Lists with some possible strategic additional value: using two Lists, eliminates the possible errors of having duplicate keys in the 'mirror' dictionary.
An example (from pre-Linq days):
// note: duplicates used deliberately
List<int> theKeys = new List<int>() { 3, 4, 7, 1, 2, 5, 6, 2 };
//
List<string> theValues = new List<string>() { "three", "four", "seven", "one", "two", "five", "six", "two" };
private string findByKey(int theKey)
{
return theKeys.Contains(theKey) ? theValues[theKeys.IndexOf(theKey)] : null;
}
private int? findByValue(string theValue)
{
// note the hack here in order
// to be able to return null
// in the case of a 'fail
int? result = null;
if (theValues.Contains(theValue)) result = theKeys[theValues.IndexOf(theValue)];
return result;
}
A sample test for out-of-bounds values (verify nulls are being returned):
string theString = findByKey(77);
int? theInt = findByValue("magic");
Now that we are smothered in Linq's glory, I will, someday, re-visit this experiment, looking at using Linq to implement select first, last, multiples, etc.
Now the "cost" of using this type of solution, of course, has to include filling the 'mirrored' Lists properly. I still really enjoy messing around with .NET Dictionaries !