Created
May 2, 2013 06:57
-
-
Save sebnilsson/5500575 to your computer and use it in GitHub Desktop.
Bi-directional Dictionary with constructors to help out with initialization
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
public class BiDictionary<TFirst, TSecond> | |
{ | |
private readonly IDictionary<TFirst, TSecond> firstToSecond; | |
private readonly IDictionary<TSecond, TFirst> secondToFirst; | |
public BiDictionary() | |
{ | |
firstToSecond = new Dictionary<TFirst, TSecond>(); | |
secondToFirst = new Dictionary<TSecond, TFirst>(); | |
} | |
public BiDictionary( | |
ICollection<KeyValuePair<TFirst, TSecond>> collection, | |
IEqualityComparer<TFirst> firstComparer = null, | |
IEqualityComparer<TSecond> secondComparer = null) | |
{ | |
firstComparer = firstComparer ?? EqualityComparer<TFirst>.Default; | |
secondComparer = secondComparer ?? EqualityComparer<TSecond>.Default; | |
this.firstToSecond = new Dictionary<TFirst, TSecond>(collection.Count, firstComparer); | |
this.secondToFirst = new Dictionary<TSecond, TFirst>(collection.Count, secondComparer); | |
foreach (var item in collection) | |
{ | |
this.firstToSecond.Add(item.Key, item.Value); | |
this.secondToFirst.Add(item.Value, item.Key); | |
} | |
} | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment