An integer array as a key for Dictionary

前端 未结 3 1580
死守一世寂寞
死守一世寂寞 2020-11-28 13:20

I wish to have the dictionary which uses an array of integers as keys, and if the integer array has the same value (even different object instance), they will be treated as

相关标签:
3条回答
  • 2020-11-28 14:07

    The easiest way if you don't care about actual hashing may just be to convert the array into a string.

    dic.Add(String.Join("",a), "haha");
    
    0 讨论(0)
  • 2020-11-28 14:09

    You can create an IEqualityComparer to define how the dictionary should compare items. If the ordering of items is relevant, then something like this should work:

    public class MyEqualityComparer : IEqualityComparer<int[]>
    {
        public bool Equals(int[] x, int[] y)
        {
            if (x.Length != y.Length)
            {
                return false;
            }
            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] != y[i])
                {
                    return false;
                }
            }
            return true;
        }
    
        public int GetHashCode(int[] obj)
        {
            int result = 17;
            for (int i = 0; i < obj.Length; i++)
            {
                unchecked
                {
                    result = result * 23 + obj[i];
                }
            }
            return result;
        }
    }
    

    Then pass it in as you create the dictionary:

    Dictionary<int[], string> dic
        = new Dictionary<int[], string>(new MyEqualityComparer());
    

    Note: calculation of hash code obtained here: What is the best algorithm for an overridden System.Object.GetHashCode?

    0 讨论(0)
  • 2020-11-28 14:22

    Maybe you should consider using a Tuple

    var myDictionary = new Dictionary<Tuple<int,int>, string>(); 
    myDictionary.Add(new Tuple<int,int>(3, 3), "haha1"); 
    myDictionary.Add(new Tuple<int,int>(5, 5), "haha2"); 
    

    According to MSDN , Tuple objects Equals method will use the values of the two Tuple objects

    0 讨论(0)
提交回复
热议问题