.NET "reversible" dictionary, where keys and values ​​are replaced

Is there any .NET type that will be a set of key-value pairs, where each key will be connected to only one value (for example, a regular Dictionary ), but also each value will be associated with only one key? I thought of it as a “reversible” dictionary, because you could change keys with values ​​without any collisions. It is easy to write such a class and add methods such as "TryGetKey" for a given value. However, I wanted to check if such a thing exists somewhere, perhaps under a different name that I did not think about.

Also, given the elegant answer to this question , would it be wise to create a class to represent this reversible dictionary, when could I just as easily use LINQ to convert any dictionary into its equivalent value?

+4
source share
2 answers

I do not believe that there is a class in the structure that does this directly.

Also, given the elegant answer to this question, would it be wise to create a class to represent this reversible dictionary, when could I just use LINQ to convert any dictionary into its equivalent value?

The answer to both of your questions really depends on how you are going to access your data. If you need fast, constant access time based on key and value, you will most likely want to create your own collection.

This can be done very, very easily. Just wrap two instances of Dictionary inside your class, and when you add a new element, add both - one with the key / value and one with the value / key. Your search routines can simply be pulled out of the appropriate collection, and it will stay next to O (1) for access time.

If, however, the memory is more worried, you can simply use one collection and use LINQ to analyze it. This will make your "reverse" search pretty slow, since you will need to reanalyze it every time.

+3
source

If you really need such a data structure, you probably won't want the overhead of converting it every time you look. That is, if you had a normal Dictionary<string,int> , every time you did a search by value, you would have to go through this conversion. You could optimize it so that you only do the conversion if the dictionary has changed (i.e. the item has been added, deleted or changed), but there will still be a pretty high price to pay.

+1
source

All Articles