I think Jon Skeet's BiDictionary
class is what you are looking for. Use it like:
BiDictionary<string, string> colors = new BiDictionary<string, string>();
colors.Add("Green", "00FF00");
colors.Add("Red", "FF0000");
colors.Add("White", "FFFFFF");
string code = colors.GetByFirst("Red");
string name = colors.GetBySecond("FF0000");
Console.WriteLine(code);
Console.WriteLine(name);
This is the class. I added GetByFirst
and GetBySecond
so that you can access it more like Dictionary
's indexer instead of like its TryGetValue
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
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 TSecond GetByFirst(TFirst first)
{
return firstToSecond[first];
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
public TFirst GetBySecond(TSecond second)
{
return secondToFirst[second];
}
}