Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As everyone else has said, there's no mapping within a dictionary from value to key.</p> <p><strong>I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.</strong></p> <p>The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:</p> <pre><code>using System; using System.Collections.Generic; class BiDictionary&lt;TFirst, TSecond&gt; { IDictionary&lt;TFirst, TSecond&gt; firstToSecond = new Dictionary&lt;TFirst, TSecond&gt;(); IDictionary&lt;TSecond, TFirst&gt; secondToFirst = new Dictionary&lt;TSecond, TFirst&gt;(); public void Add(TFirst first, TSecond second) { if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second)) { throw new ArgumentException("Duplicate first or second"); } firstToSecond.Add(first, second); secondToFirst.Add(second, first); } public bool TryGetByFirst(TFirst first, out TSecond second) { return firstToSecond.TryGetValue(first, out second); } public bool TryGetBySecond(TSecond second, out TFirst first) { return secondToFirst.TryGetValue(second, out first); } } class Test { static void Main() { BiDictionary&lt;int, string&gt; greek = new BiDictionary&lt;int, string&gt;(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); int x; greek.TryGetBySecond("Beta", out x); Console.WriteLine(x); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload