Search code examples
c#dictionaryhashtabletuples

Tuples (or arrays) as Dictionary keys in C#


I am trying to make a Dictionary lookup table in C#. I need to resolve a 3-tuple of values to one string. I tried using arrays as keys, but that did not work, and I don't know what else to do. At this point I am considering making a Dictionary of Dictionaries of Dictionaries, but that would probably not be very pretty to look at, though it is how I would do it in javascript.


Solution

  • If you are on .NET 4.0 use a Tuple:

    lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
    

    If not you can define a Tuple and use that as the key. The Tuple needs to override GetHashCode, Equals and IEquatable:

    struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>>
    {
        readonly T first;
        readonly U second;
        readonly W third;
    
        public Tuple(T first, U second, W third)
        {
            this.first = first;
            this.second = second;
            this.third = third;
        }
    
        public T First { get { return first; } }
        public U Second { get { return second; } }
        public W Third { get { return third; } }
    
        public override int GetHashCode()
        {
            return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode();
        }
    
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            return Equals((Tuple<T, U, W>)obj);
        }
    
        public bool Equals(Tuple<T, U, W> other)
        {
            return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third);
        }
    }