Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What could be used as a double sided Resource Dictionary?

I am using a ResourceDictionary, but I would like to be able to look up the value or the key with the other item. Each is always unique, so that is not a problem. Is there a type that has this double sided lookup feature?

like image 656
Totty Avatar asked Nov 18 '08 19:11

Totty


2 Answers

Not built in, but this is pretty easy to write. I would probably implement IDictionary for this though... You would then dump the ResourceDictionary into your custom 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];
  }


}
like image 138
Craig Wilson Avatar answered Sep 23 '22 16:09

Craig Wilson


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

The contract of the dictionary guarantees that, for every value in the collection, there is exactly one key which maps to that value. The keys are unique. But the reverse is not true; for every distinct value, there can be many different keys mapping to that value.

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

When I need to perform value-to-key lookups 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 a MultiMap (like a HashMap or Dictionary) as your reverse-lookup table, you run the risk of losing some of your V->K mappings, unless you can guarantee that all keys AND all values in your collection are unique.


EDIT:

Oops. I just noticed that you said that all keys and values in your collection are unique. But I'll leave my answer here anyhow, as a warning for others reading this, who might not be able to provide the same guarantee.

like image 29
benjismith Avatar answered Sep 25 '22 16:09

benjismith