One use of Lookup
could be to reverse a Dictionary
.
Suppose you have a phonebook implemented as a Dictionary
with a bunch of (unique) names as keys, each name associated with a phone number. But two people with different names might share the same phone number. This isn't a problem for a Dictionary
, which doesn't care that two keys correspond to the same value.
Now you want a way of looking up who a given phone number belongs to. You build a Lookup
, adding all the KeyValuePairs
from your Dictionary
, but backwards, with the value as the key and the key as the value. You can now query a phone number, and obtain a list of names of all the people whose phone number that is. Building a Dictionary
with the same data would drop data (or fail, depending on how you did it), since doing
dictionary["555-6593"] = "Dr. Emmett Brown";
dictionary["555-6593"] = "Marty McFly";
means that the second entry overwrites the first - the Doc is no longer listed.
Trying to write the same data in a slightly different way:
dictionary.Add("555-6593", "Dr. Emmett Brown");
dictionary.Add("555-6593", "Marty McFly");
would throw an exception on the second line since you can't Add
a key which is already in the Dictionary
.
[Of course, you might want to use some other single data structure to do lookups in both directions, etc. This example means that you have to regenerate the Lookup
from the Dictionary
each time the latter changes. But for some data it could be the right solution.]