BidirectionalDictionary has wondeful design to add, remove & search 2 columns

BidirectionalDictionary stores the two columns in 2 Dictionary with the value of two columns as KEY, it makes it easier to search, remove and add. The drawback is only more memory is used.

Here,

Two Columns: 2 Dictionary is used
Three Columns: 6 Dictionary would be used ( 1-2, 1-3, 2-1, 2-3, 3-1, 3-2)


   public class BidirectionalDictionary<TFirst, TSecond>
    {
        readonly IDictionary<TFirst, TSecond> _firstToSecond = new Dictionary<TFirst, TSecond>();
        readonly 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 void RemoveByFirst(TFirst first)
        {
            TSecond second;
            if (TryGetByFirst(first, out second))
            {
                _firstToSecond.Remove(first);
                _secondToFirst.Remove(second);  
            }
        }

留言