Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Okay, here's the multiple bidirectional version:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; class BiDictionary&lt;TFirst, TSecond&gt; { IDictionary&lt;TFirst, IList&lt;TSecond&gt;&gt; firstToSecond = new Dictionary&lt;TFirst, IList&lt;TSecond&gt;&gt;(); IDictionary&lt;TSecond, IList&lt;TFirst&gt;&gt; secondToFirst = new Dictionary&lt;TSecond, IList&lt;TFirst&gt;&gt;(); private static IList&lt;TFirst&gt; EmptyFirstList = new TFirst[0]; private static IList&lt;TSecond&gt; EmptySecondList = new TSecond[0]; public void Add(TFirst first, TSecond second) { IList&lt;TFirst&gt; firsts; IList&lt;TSecond&gt; seconds; if (!firstToSecond.TryGetValue(first, out seconds)) { seconds = new List&lt;TSecond&gt;(); firstToSecond[first] = seconds; } if (!secondToFirst.TryGetValue(second, out firsts)) { firsts = new List&lt;TFirst&gt;(); secondToFirst[second] = firsts; } seconds.Add(second); firsts.Add(first); } // Note potential ambiguity using indexers (e.g. mapping from int to int) // Hence the methods as well... public IList&lt;TSecond&gt; this[TFirst first] { get { return GetByFirst(first); } } public IList&lt;TFirst&gt; this[TSecond second] { get { return GetBySecond(second); } } public IList&lt;TSecond&gt; GetByFirst(TFirst first) { IList&lt;TSecond&gt; list; if (!firstToSecond.TryGetValue(first, out list)) { return EmptySecondList; } return new List&lt;TSecond&gt;(list); // Create a copy for sanity } public IList&lt;TFirst&gt; GetBySecond(TSecond second) { IList&lt;TFirst&gt; list; if (!secondToFirst.TryGetValue(second, out list)) { return EmptyFirstList; } return new List&lt;TFirst&gt;(list); // Create a copy for sanity } } 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"); greek.Add(5, "Beta"); ShowEntries(greek, "Alpha"); ShowEntries(greek, "Beta"); ShowEntries(greek, "Gamma"); } static void ShowEntries(BiDictionary&lt;int, string&gt; dict, string key) { IList&lt;int&gt; values = dict[key]; StringBuilder builder = new StringBuilder(); foreach (int value in values) { if (builder.Length != 0) { builder.Append(", "); } builder.Append(value); } Console.WriteLine("{0}: [{1}]", key, builder); } } </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