Two-Way/Bidirectional Dictionary in C#

Two-way / bidirectional Dictionary in C#?

I wrote a quick couple of classes that lets you do what you want. You'd probably need to extend it with more features, but it is a good starting point.

The use of the code looks like this:

var map = new Map<int, string>();

map.Add(42, "Hello");

Console.WriteLine(map.Forward[42]);
// Outputs "Hello"

Console.WriteLine(map.Reverse["Hello"]);
//Outputs 42

Here's the definition:

public class Map<T1, T2>
{
private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
private Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();

public Map()
{
this.Forward = new Indexer<T1, T2>(_forward);
this.Reverse = new Indexer<T2, T1>(_reverse);
}

public class Indexer<T3, T4>
{
private Dictionary<T3, T4> _dictionary;
public Indexer(Dictionary<T3, T4> dictionary)
{
_dictionary = dictionary;
}
public T4 this[T3 index]
{
get { return _dictionary[index]; }
set { _dictionary[index] = value; }
}
}

public void Add(T1 t1, T2 t2)
{
_forward.Add(t1, t2);
_reverse.Add(t2, t1);
}

public Indexer<T1, T2> Forward { get; private set; }
public Indexer<T2, T1> Reverse { get; private set; }
}

Bidirectional 1 to 1 Dictionary in C#

OK, here is my attempt (building on Jon's - thanks), archived here and open for improvement :

/// <summary>
/// This is a dictionary guaranteed to have only one of each value and key.
/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.
/// </summary>
/// <typeparam name="TFirst">The type of the "key"</typeparam>
/// <typeparam name="TSecond">The type of the "value"</typeparam>
public class BiDictionaryOneToOne<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

#region Exception throwing methods

/// <summary>
/// Tries to add the pair to the dictionary.
/// Throws an exception if either element is already in the dictionary
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
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);
}

/// <summary>
/// Find the TSecond corresponding to the TFirst first
/// Throws an exception if first is not in the dictionary.
/// </summary>
/// <param name="first">the key to search for</param>
/// <returns>the value corresponding to first</returns>
public TSecond GetByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
throw new ArgumentException("first");

return second;
}

/// <summary>
/// Find the TFirst corresponing to the Second second.
/// Throws an exception if second is not in the dictionary.
/// </summary>
/// <param name="second">the key to search for</param>
/// <returns>the value corresponding to second</returns>
public TFirst GetBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
throw new ArgumentException("second");

return first;
}

/// <summary>
/// Remove the record containing first.
/// If first is not in the dictionary, throws an Exception.
/// </summary>
/// <param name="first">the key of the record to delete</param>
public void RemoveByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
throw new ArgumentException("first");

firstToSecond.Remove(first);
secondToFirst.Remove(second);
}

/// <summary>
/// Remove the record containing second.
/// If second is not in the dictionary, throws an Exception.
/// </summary>
/// <param name="second">the key of the record to delete</param>
public void RemoveBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
throw new ArgumentException("second");

secondToFirst.Remove(second);
firstToSecond.Remove(first);
}

#endregion

#region Try methods

/// <summary>
/// Tries to add the pair to the dictionary.
/// Returns false if either element is already in the dictionary
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns>true if successfully added, false if either element are already in the dictionary</returns>
public Boolean TryAdd(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
return false;

firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
return true;
}

/// <summary>
/// Find the TSecond corresponding to the TFirst first.
/// Returns false if first is not in the dictionary.
/// </summary>
/// <param name="first">the key to search for</param>
/// <param name="second">the corresponding value</param>
/// <returns>true if first is in the dictionary, false otherwise</returns>
public Boolean TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}

/// <summary>
/// Find the TFirst corresponding to the TSecond second.
/// Returns false if second is not in the dictionary.
/// </summary>
/// <param name="second">the key to search for</param>
/// <param name="first">the corresponding value</param>
/// <returns>true if second is in the dictionary, false otherwise</returns>
public Boolean TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}

/// <summary>
/// Remove the record containing first, if there is one.
/// </summary>
/// <param name="first"></param>
/// <returns> If first is not in the dictionary, returns false, otherwise true</returns>
public Boolean TryRemoveByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
return false;

firstToSecond.Remove(first);
secondToFirst.Remove(second);
return true;
}

/// <summary>
/// Remove the record containing second, if there is one.
/// </summary>
/// <param name="second"></param>
/// <returns> If second is not in the dictionary, returns false, otherwise true</returns>
public Boolean TryRemoveBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
return false;

secondToFirst.Remove(second);
firstToSecond.Remove(first);
return true;
}

#endregion

/// <summary>
/// The number of pairs stored in the dictionary
/// </summary>
public Int32 Count
{
get { return firstToSecond.Count; }
}

/// <summary>
/// Removes all items from the dictionary.
/// </summary>
public void Clear()
{
firstToSecond.Clear();
secondToFirst.Clear();
}
}

Data structure for two way mapping

Why wouldn't a custom type with two dictionaries work? Although it will use double the memory, it allows for O(1) lookup and should work as you want.

However, when it comes to the generic parameters, it can get a bit hairy. If you specify the same type it's not a problem, however if you specify a different type the indexer breaks because you can only get a value out one way. If you overload the indexer and have two, i.e.:

public K this[T value]
public T this[K value]

It will break if you have the same arguments because it won't be able to resolve. In that case, I would suggest having two different classes:

public class TwoWayDictionary<T>
{
private Dictionary<T, T> _first;
private Dictionary<T, T> _second;

public TwoWayDictionary()
{
_first = new Dictionary<T, T>();
_second = new Dictionary<T, T>();
}

public void Add(T first, T second)
{
_first.Add(first, second);
_second.Add(second, first);
}

public T this[T value]
{
get
{
if(_first.ContainsKey(value))
{
return _first[value];
}
if(_second.ContainsKey(value))
{
return _second[value];
}

throw new ArgumentException(nameof(value));
}
}
}

and

public class TwoWayDictionary<T, K>
{
private readonly Dictionary<T, K> _first;
private readonly Dictionary<K, T> _second;

public TwoWayDictionary()
{
_first = new Dictionary<T, K>();
_second = new Dictionary<K, T>();
}

public void Add(T first, K second)
{
_first.Add(first, second);
_second.Add(second, first);
}

public K this[T value]
{
get
{
if (_first.ContainsKey(value))
{
return _first[value];
}

throw new ArgumentException(nameof(value));
}
}

public T this[K value]
{
get
{
if (_second.ContainsKey(value))
{
return _second[value];
}

throw new ArgumentException(nameof(value));
}
}
}

This will allow you to use it like mentioned in the comments:

var dict = new TwoWayDictionary<string>();
dict.Add(".jpg", "image/jpg");
var mime = dict[".jpg"];
var ext = dict["image/jpg"];

and specify 2 different types if you want:

var dict = new TwoWayDictionary<string, int>();
dict.Add(".jpg", 100);
var number = dict[".jpg"];
var ext = dict[100];

Bi-directional dictionary?

Someone with better knowledge of data structures could probably give better advice, but personally, I'd use 2 dictionaries for ease of use. You could do the same with 1 dictionary but access time would increase.

Edit: crap, I was just in the process of writing up some code how I would do it and I saw that Falaina posted this which is the same idea that I was doing only much better: Getting key of value of a generic Dictionary?

Two-Way Mapping list

You can use a dictionary easily enough as a two-way mapping if you don't care about linear search performance for the reverse mapping (which you'd get with a 2D array anyway):

var dictionary = new Dictionary<string, int>();
// Fill it up...
int forwardMapResult = dictionary["SomeKey"];
string reverseMapResult = dictionary.Where(kvp => kvp.Value == 5).First().Key;

If the lookup speed is an issue than you'll have to maintain two dictionaries - one for the forward lookup and one for the reverse. Or use an in-memory, indexable database such as SQLite.

how to create a two way int-string dictionary?

I already solved the problem. I created my own class. It contains a list of strings (names) and a list of objects of any type. It has 6 get methods that can interchange between the string, int and object any way.

A two way KeyValuePair collection in C#

It sounds like you need a bi-directional dictionary. There are no framework classes that support this, but you can implement your own:

Bidirectional 1 to 1 Dictionary in C#

How can I implement a dictionary whose value is also a key?

what you're looking for is also called a Two-way dictionary. Take a look at other SO answers to the same question.



Related Topics



Leave a reply



Submit