Bidirectional 1 to 1 Dictionary in C#

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();
}
}

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; }
}

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?

Use collection initializer for BiDirection dictionary

The easiest is probably to enumerate the elements of the forward (or backward, whatever seems more natural) dictionary like so:

internal class BiDirectionContainer<T1, T2> : IEnumerable<KeyValuePair<T1, T2>>
{
private readonly Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
private readonly Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();

internal T2 this[T1 key] => _forward[key];

internal T1 this[T2 key] => _reverse[key];

IEnumerator<KeyValuePair<T1, T2>> IEnumerable<KeyValuePair<T1, T2>>.GetEnumerator()
{
return _forward.GetEnumerator();
}

public IEnumerator GetEnumerator()
{
return _forward.GetEnumerator();
}

internal void Add(T1 element1, T2 element2)
{
_forward.Add(element1, element2);
_reverse.Add(element2, element1);
}
}

As an aside: If you only want to be able to use collection initializer, it is required by the C# language specification that your class implements System.Collections.IEnumerable and also provides an Add method that is applicable for each element initializer (i.e. basically number and type of arguments must match). The interface is required by the compiler, but the GetEnumerator method is not called when the collection is initialized (only the add method is). It is required because the collection initializer should only be available for things that actually are a collection and not just something that has an add method. Therefore it is fine to just add the interface without actually implementing a method body (public IEnumerator GetEnumerator(){ throw new NotImplementedException(); })

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];

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.

Looking for a datastructure with a 1-to-1 unique dependency

Could this method fit your needs?

public static class Extensions
{
public static TKey GetKey<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue value)
{
int index = dict.Values.ToList().IndexOf(value);

if (index == -1)
{
return default(TKey); //or maybe throw an exception
}

return dict.Keys.ToList()[index];
}
}

You could then use it like so:

Dictionary<int, char> dict = new Dictionary<int, char>();
dict.Add(1, 'a');
dict.Add(4, 'b');
dict.Add(6, 'c');
dict.Add(5, 'd');

Console.WriteLine(dict.GetKey('d')); //5


Related Topics



Leave a reply



Submit