Last active
April 2, 2017 06:47
-
-
Save ccrossley/88cdf9465dbd861645faa9d8488dceca to your computer and use it in GitHub Desktop.
A Bidirectional Dictionary. BiDirectionary...here.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class BiDirectionary<Primary, Secondary> : IEnumerable<KeyValuePair<Primary, Secondary>> { | |
private Dictionary<Primary, Secondary> forwards; | |
private Dictionary<Secondary, Primary> backwards; | |
public BiDirectionary() { | |
forwards = new Dictionary<Primary, Secondary> (); | |
backwards = new Dictionary<Secondary, Primary> (); | |
} | |
virtual public bool Contains(Primary p) { | |
return forwards.ContainsKey(p); | |
} | |
public bool Contains(Secondary s) { | |
return backwards.ContainsKey(s); | |
} | |
public void Add(Primary p, Secondary s) { | |
if (forwards.ContainsKey(p) || p == null || s == null) { | |
return; | |
} | |
forwards.Add(p, s); | |
backwards.Add(s, p); | |
} | |
public void Remove(Primary p) { | |
if (p == null) { | |
return; | |
} | |
if (forwards.ContainsKey(p)) { | |
var s = forwards [p]; | |
forwards.Remove(p); | |
backwards.Remove(s); | |
} | |
} | |
public void Remove(Secondary s) { | |
if (s != null) { | |
Remove(this [s]); | |
} | |
} | |
public int Count { | |
get { return forwards.Count; } | |
} | |
public Secondary Get(Primary p) { | |
return (forwards.ContainsKey(p)) ? forwards [p] : default(Secondary); | |
} | |
public Primary Get(Secondary s) { | |
return (backwards.ContainsKey(s)) ? backwards [s] : default(Primary); | |
} | |
public bool TryGet(Primary p, out Secondary s) { | |
if (!forwards.ContainsKey(p)) { | |
s = default(Secondary); | |
return false; | |
} | |
s = Get(p); | |
return true; | |
} | |
public bool TryGet(Secondary s, out Primary p) { | |
if (!backwards.ContainsKey(s)) { | |
p = default(Primary); | |
return false; | |
} | |
p = Get(s); | |
return true; | |
} | |
public Secondary this[Primary p] { | |
get { return Get(p); } | |
set { Add(p, value); } | |
} | |
public Primary this[Secondary s] { | |
get { return Get(s); } | |
set { Add(value, s); } | |
} | |
virtual public void Clear() { | |
forwards.Clear(); | |
backwards.Clear(); | |
} | |
#region IEnumerable implementation | |
public IEnumerator<KeyValuePair<Primary, Secondary>> GetEnumerator() { | |
foreach (var kv in forwards) { | |
yield return kv; | |
} | |
} | |
#endregion | |
#region IEnumerable implementation | |
IEnumerator IEnumerable.GetEnumerator() { | |
return GetEnumerator(); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment