Created
January 6, 2016 15:14
-
-
Save otuncelli/2c43cf338162eac9b02b to your computer and use it in GitHub Desktop.
Bi-directional Dictionary Implementation
This file contains hidden or 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; | |
namespace BiDictionary | |
{ | |
public sealed class BiDictionary<T1, T2> : IEnumerable<KeyValuePair<T1, T2>> | |
{ | |
readonly Dictionary<T1, T2> first; | |
readonly Dictionary<T2, T1> second; | |
public BiDictionary() | |
{ | |
first = new Dictionary<T1, T2>(); | |
second = new Dictionary<T2, T1>(); | |
} | |
public BiDictionary(int capacity) | |
{ | |
first = new Dictionary<T1, T2>(capacity); | |
second = new Dictionary<T2, T1>(capacity); | |
} | |
public BiDictionary(IDictionary<T1, T2> collection) | |
: this(collection.Count) | |
{ | |
foreach (KeyValuePair<T1, T2> kvp in collection) | |
{ | |
first.Add(kvp.Key, kvp.Value); | |
second.Add(kvp.Value, kvp.Key); | |
} | |
} | |
public IDictionary<T1, T2> First | |
{ | |
get { return first; } | |
} | |
public IDictionary<T2, T1> Second | |
{ | |
get { return second; } | |
} | |
public void Add(T1 key, T2 value) | |
{ | |
first.Add(key, value); | |
second.Add(value, key); | |
} | |
public T2 GetValueByKey(T1 key) | |
{ | |
return first[key]; | |
} | |
public T1 GetKeyByValue(T2 value) | |
{ | |
return second[value]; | |
} | |
public IEnumerable<T1> Keys | |
{ | |
get { return first.Keys; } | |
} | |
public IEnumerable<T2> Values | |
{ | |
get { return first.Values; } | |
} | |
public T Get<T>(T key_OR_value) where T : IConvertible | |
{ | |
if (typeof(T) == typeof(T1)) | |
{ | |
T1 key = (T1)Convert.ChangeType(key_OR_value, typeof(T1)); | |
T2 result; | |
if (first.TryGetValue(key, out result)) | |
return (T)Convert.ChangeType(result, typeof(T)); | |
} | |
if (typeof(T) == typeof(T2)) | |
{ | |
T2 key = (T2)Convert.ChangeType(key_OR_value, typeof(T2)); | |
T1 result; | |
if (second.TryGetValue(key, out result)) | |
return (T)Convert.ChangeType(result, typeof(T)); | |
} | |
throw new KeyNotFoundException(key_OR_value.ToString()); | |
} | |
public IEnumerator<KeyValuePair<T1, T2>> GetEnumerator() | |
{ | |
return first.GetEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return first.GetEnumerator(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment