Array comprasion as Dictionary keys in C#

后端 未结 3 391
闹比i
闹比i 2021-01-20 01:42

I want to create class representing n-dimensional array, but where is a commutative access to its elements. e.g: a[new[] {4, 7, 55}] == a[new[] {55, 4, 7}]

相关标签:
3条回答
  • 2021-01-20 01:50

    To me seems that GetHashCode have to be changed as it simply returns the hash code of Array object, considering the fact that you use NEW hashcode every time will be different, even if content equal.

    0 讨论(0)
  • 2021-01-20 02:01

    Since you're using a Dictionary to store your arrays you need to check if the key exists already, and only then can you access it with the [] operator, otherwise if you try to access a key that doesn't exist an exception is thrown

    // your get function
    if(array.ContainsKey(x))
        return array[x];
    else // do something like return null
        return null;
    
    // your set function
    if(array.ContainsKey(x))
        array[x] = value;
    else
        array.Add(x, value);
    
    0 讨论(0)
  • 2021-01-20 02:02

    That's because your implementation of GetHashCode is incorrect: two different arrays with the same items in the same order usually won't have the same hashcode (because the values are not taken into account), so Equals is never called.

    You need an implementation of GetHashCode that takes the values in the array into account:

    class ArrCmpr : IEqualityComparer<int[]>
    {
        public bool Equals(int[] a, int[] b)
        {
            return a.SequenceEqual(b);
        }
    
        public int GetHashCode(int[] a)
        {
            return a.Aggregate(0, (acc, i) => unchecked(acc * 457 + i * 389));
        }
    }
    
    0 讨论(0)
提交回复
热议问题