What can be used as a two-way resource dictionary?

I am using ResourceDictionary, but I would like to be able to look up a value or key with another element. Each of them is always unique, so this is not a problem. Is there a type that has this two-way search function?

+6
c # resourcedictionary
source share
2 answers

Not built in, but it's pretty easy to write. I would probably use an IDictionary for this, though ... Then you unloaded the ResourceDictionary into your own type.

public class DoubleLookup<TKey, TValue> { private IDictionary<TKey, TValue> keys; private IDictionary<TValue, TKey> values; //stuff... public void Add(TKey key, TValue value) { this.keys.Add(key, value); this.values.Add(value, key); } public TKey GetKeyFromValue(TValue value) { return this.values[value]; } public TValue GetValueFromKey(TKey key) { return this.keys[key]; } } 
+7
source share

Be very careful when changing the key / value relationship in the dictionary.

The dictionary contract ensures that for each value in the collection there is exactly one key that maps to this value. The keys are unique. But the converse is not true; for each individual value there can be many different keys matching this value.

In my own personal code library (written in Java, which is pretty close), I have a MultiMap class for this kind of thing. Although keys are unique, each key can be associated with multiple values. It is exactly identical to Map>.

When I need to search for keywords in a collection, I do something like this:

 Map<K, V> lookupTable = ...; MultiMap<V, K> reverseLookupTable = MapUtil.invert(lookupTable); V value = ...; if (reverseLookupTable.containsKey(value)) { Set<K> keys = reverseLookupTable.get(value); } 

If you use something other than MultiMap (like HashMap or Dictionary) as your reverse lookup table, you risk losing some of your V-> K mappings, unless you can guarantee that all keys and all values ​​in your collection are unique.


EDIT:

Unfortunately. I just noticed that you said that all the keys and values ​​in your collection are unique. But I will leave my answer here in any case, as a warning to others reading this who may not be able to provide the same guarantee.

+2
source share

All Articles