Array comprasion as Dictionary keys in C#

后端 未结 3 394
闹比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 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
    {
        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));
        }
    }
    

提交回复
热议问题